两个条件检查where子句使用linq 2 [英] two conditions checking in where clause using linq 2 entites

查看:69
本文介绍了两个条件检查where子句使用linq 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有表名称产品列

                 product_id
                 prodcut_name
                 prodcut_price( values like 1200,2000,3000,100)
                 prodcut_desc
                 category_id(1,2,3,.....) 

anorther table categories with columns

anorther table categories with columns

              category_id(1,2,3.......)
              category_name(a,b,c....)

和实体名称是dbcontext ...

and entity name is dbcontext...

如何获取类别名称为a的产品,产品价格为> 500,< 10000

How can i get the products with category name "a" and product price is >500 and <10000

我正在使用linq的恩赐...

i am using linq to enitities...

将有任何帮助这个... ... ...

would any pls help on this..one ....

非常感谢....

推荐答案

您正在寻找逻辑运算符,而这些你将要在c#中使用:

You are looking for logic operators, and these are you are going to use in c#:


  • && code>和

  • || logical OR

  • logical NOT

  • ^ 逻辑(按位) XOR

  • COND? TRUE-STATEMENT:FALSE-STATEMENT 三元运算符

  • && logical AND
  • || logical OR
  • ! logical NOT
  • ^ logical (bitwise) XOR
  • COND ? TRUE-STATEMENT : FALSE-STATEMENT ternary operator

所以你的伪代码中的复合条件看起来像:

So your composite condition in pseudo code going to look like:

(product_price > 500) && (product_price < 10000)

现在,如果在DB中没有外键,创建了您的上下文,它只会拥有DBSets,并且它们不会具有导航属性。所以你唯一的选择是使用Cubicle.Jockey的答案。

Now, if you have no foreign key in DB, when you've created your context it only going to have DBSets, and they are not going to have navigation properties. So your only option is to use Cubicle.Jockey's answer.

如果在DB中有外键,那么您的实体对象将具有导航属性,您将可以请执行以下操作:

If you have foreign keys in DB, you will have navigation properties on your entity objects and you will be able to do the following:

var query = from p in dbcontext.products
where p.category.name == 'a' 
   && p.product_price > 500 
   && p.product_price < 10000
select p;

或者您可以直接使用LINQ扩展方法:

Alternatively you can use LINQ extension methods directly:

  var query = dbcontext.Products.Where(p => p.category.name == 'a' 
                                         && p.product_price > 500 
                                         && p.product_price < 10000);

如果您需要一个列表或数组,并希望关闭dbcontext,您调用 ToArray 查询

If you need a list or array and want close dbcontext you are calling either ToList or ToArray on query:

var products = query.ToList();

有实现框架(EF)的另一种方法 - 内置 EntitySQL 查询语言。你将会有类似的表达:

There is alternative way of doing it with Entity Framework (EF) - build-in EntitySQL query language. You are going to have similar expression with it:

var query = ProductsQuery.Where("it.Category.Name == 'a' AND it.Product_Price BETWEEN 500 AND 10000");

其中 ProdocutsQuery ObjectQuery< Product>

这篇关于两个条件检查where子句使用linq 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆