2016-08-18 51 views
2

是否可以从列表中指定“包含”?Linq从列表中包含<string>

我有可能的子表列表将包含在:

List<string> includedTables 

我现在的数据库调用看起来是这样的:

return db.SA_Items 
     .Where(x => x.LastUpdated > lastUpdated) 
     .Where(x => x.Active == true) 
     .OrderBy(x => x.ItemID) 
     .Skip(offset) 
     .Take(limit) 
     .ToList(); 

我会以某种方式在列表中的foreach串并在数据库调用中添加.Include(....) ...

例如,如果列表中有2个字符串,则代码将与此等效:

return db.SA_Items 
     .Include("first string in the list") 
     .Include("second string in the list") 
     .Where(x => x.LastUpdated > lastUpdated) 
     .Where(x => x.Active == true) 
     .OrderBy(x => x.ItemID) 
     .Skip(offset) 
     .Take(limit) 
     .ToList(); 

List也可能为空。

是否可以动态地做到这一点?

任何人都可以给我任何指针吗?

+1

@Fabjan,就必须要急于负载相关的实体,即提出Include'方法 – octavioccl

回答

2

当然,你可以建立自己的查询在几个步骤:

IQueryable<SA_Item> query=db.SA_Items; 
if(includedTables!=null) 
    query = includedTables.Aggregate(query, (current, include) => current.Include(include)); 

query=query.Where(x => x.LastUpdated > lastUpdated) 
      .Where(x => x.Active == true) 
      .OrderBy(x => x.ItemID) 
      .Skip(offset) 
      .Take(limit); 
return query.ToList();// Materialize your query 
+0

我收到错误的':“无法隐式转换类型“System.Data.Entity.Infrastructure.DbQuery < SADatastore.SA_Items>'改为'System.Data.Entity.DbSet '。在current.Include(include)部分中存在明确的转换(你是否缺少一个转换?)“:( –

+0

这就是有道理,用'IQueryable '类型来代替'var'来保存你的查询。这应该可以解决问题。 – octavioccl

+0

真的很抱歉,现在它说“System.Linq.IQueryable '不包含定义'Include'并且没有扩展方法'Include'接受类型为'System.Linq.IQueryable '可以找到(你是否缺少使用指令或程序集引用?)“ –

0

你可以用concat做到这一点。

return db.SA_Items 
     .Concat(new string[] {"first string in the list", "second string in the list"}) 
     .Where(x => x.LastUpdated > lastUpdated) 
     .Where(x => x.Active == true) 
     .OrderBy(x => x.ItemID) 
     .Skip(offset) 
     .Take(limit) 
     .ToList();