我是实体框架的新手。我需要开发基于订单和客户的 Linq 查询。
例如:字符串 firstName 可以具有三个值中的任何一个
1) 空2)乔3) 喜欢 %乔%'
西马拉里我需要为姓氏开发
我目前的查询是这样的
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) )
}
我的查询是否正确。是否有任何其他更好的选择来编写 linq 实体查询。
谢谢
您可以向可查询对象添加条件。 在执行数据查询之前,条件将逐渐增加。
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));
您可以将查询分成几部分,然后更好:
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))
此外,检查o.firstName == firstName
是多余的,Contains(firstName)
部分就足够了(姓氏相同)。
您可以分步构建查询:
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
}
查询不会执行,直到您执行 ToList() 或在 foreach
或类似的东西中使用它。