动态构建LINQ到实体的子句

时间:2014-12-28 07:00:19

标签: c# linq entity-framework linq-to-sql linq-to-entities

如何动态构建where子句,有时OwnerID将为零itemID并且LocationID将作为搜索条件提供,在这种情况下,LINQ应该是

(from s in repository.ItemOwners.Include("OwnerDetails")
 where s.ItemId == searchCriteria.ItemID && 
       s.OwnerDetails.LocationId == searchCriteria.LocationID
 select new { s.OwnerDetails.OwnerName, s.OwnerDetails.MobNumber }).ToList();

有些时候OwnerIDItemId将为零,那么只会提供LocationID作为搜索条件,在这种情况下,LINQ应为

(from s in repository.ItemOwners.Include("OwnerDetails")
 where s.OwnerDetails.LocationId == searchCriteria.LocationID
 select new { s.OwnerDetails.OwnerName, s.OwnerDetails.MobNumber }).ToList();

有时整个OwnerIDItemIDLocationID将作为搜索条件提供,那么LINQ将会是这样的

(from s in repository.ItemOwners.Include("OwnerDetails")
 where s.OwnerId == searchCriteria.OwnerID && 
       s.ItemId == searchCriteria.ItemID && 
       s.OwnerDetails.LocationId == searchCriteria.LocationID
 select new { s.OwnerDetails.OwnerName, s.OwnerDetails.MobNumber }).ToList();

这里只有where条款正在改变,请帮我解决。我如何动态构建where子句(请注意,这里我的导航属性为OwnerDetails.LocationId)。

2 个答案:

答案 0 :(得分:3)

您可以使用基于方法的查询轻松完成此操作。您可以一次添加一个条件,并在结尾处致电SelectToList

// Where(x => true) might not be necessary, you can try skipping it.
var query = repository.ItemOwners.Include("OwnerDetails").Where(x => true);

if (searchCriteria.OwnerID != null)
    query = query.Where(s => s.OwnerID == searchCriteria.OwnerID);
if (searchCriteria.ItemID != null)
    query = query.Where(s => s.ItemID == searchCriteria.ItemID);
if (searchCriteria.OwnerID != null)
    query = query.Where(s => s..OwnerDetails.LocationId == searchCriteria.LocationID);

var results = query.Select(s => new { s.OwnerDetails.OwnerName, s.OwnerDetails.MobNumber }).ToList();

答案 1 :(得分:0)

最简单的只是检查Where子句中的零条件:

(from s in repository.ItemOwners.Include("OwnerDetails")
where (searchCriteria.OwnerID == 0 || s.OwnerId == searchCriteria.OwnerID) && 
(searchCriteria.ItemID == 0 || s.ItemId == searchCriteria.ItemID) && 
s.OwnerDetails.LocationId == searchCriteria.LocationID
select new { s.OwnerDetails.OwnerName, s.OwnerDetails.MobNumber }).ToList();