[英]dynamic where clause entity framework 3.5
I am new to entity framework. 我是实体框架的新手。 I need to develop a Linq query based on Orders and Customers. 我需要基于订单和客户开发Linq查询。
for eg: string firstName can have any of the three values 例如:string firstName可以包含三个值中的任何一个
1) null 2) Joe 3) like %Joe%' 1)null 2)Joe 3)喜欢%Joe%'
simailary i need to develop for lastname simailary我需要开发姓氏
My current query is like this 我目前的查询是这样的
using (NorthwindEntities ent = new NorthwindEntities())
{
var UsersList = ent.User.Include("Orders").
Include("OrderDetails").
Include("OrderDetails.Products").
.Where(o => (firstName== null || o.firstName== firstName||o.firstName.Contains(firstName))
&& (LastName== null || o.LastName== LastName ||o.LastName.contains(LastName) )
}
Is my query is correct. 我的查询是否正确。 Is any other better option to write linq entity query. 是否有任何其他更好的选择来编写linq实体查询。
Thanks 谢谢
you can split your query in parts, its somewhat nicer then: 你可以将你的查询分成几部分,然后它会更好一些:
var UsersList = ent.User.Include("Orders")
.Include("OrderDetails")
.Include("OrderDetails.Products");
if(!string.IsNullOrEmpty(firstName));
UsersList = UsersList.Where( o => o.firstName.Contains(firstName));
if(!string.IsNullOrEmpty(lastName));
UsersList = UsersList.Where( o => o.lastName.Contains(lastName))
Also the check o.firstName == firstName
is redundant, the Contains(firstName)
part is sufficient (same for lastName). 另外,检查o.firstName == firstName
是多余的, Contains(firstName)
部分是足够的(对于lastName是相同的)。
You can add conditions to a Queryable object. 您可以向Queryable对象添加条件。 The conditions will build up until the data query is executed. 条件将建立,直到执行数据查询。
var UsersList = ent.User.Include("Orders")
.Include("OrderDetails")
.Include("OrderDetails.Products");
if (!string.IsNullOrEmpty(firstName))
UsersList = UsersList.Where( o => o.firstName.Contains(firstName));
if (!string.IsNullOrEmpty(LastName))
UsersList = UsersList.Where( o => o.LastName.Contains(LastName));
You could build up your query in steps: 您可以按步骤构建查询:
using (NorthwindEntities ent = new NorthwindEntities())
{
var UsersList = ent.User.Include("Orders")
.Include("OrderDetails")
.Include("OrderDetails.Products");
if (LastName != null)
UserList = UserList.Where(o => o.LastName == LastName || o.LastName.contains(LastName));
if (FirstName != null)
UserList = UserList.Where(o => o.firstName== firstName||o.firstName.Contains(firstName);
// etc
}
The query won't execute until you do a ToList() or use it in a foreach
or something like that. 在执行ToList()或在foreach
或类似的东西中使用它之前,查询将不会执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.