2016-08-18 52 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();