C# Linq从列表中包括<;字符串>;
可以从列表中指定“包括”吗 我有一个可能的子表列表,包括在:C# Linq从列表中包括<;字符串>;,c#,entity-framework,linq,C#,Entity Framework,Linq,可以从列表中指定“包括”吗 我有一个可能的子表列表,包括在: List<string> includedTables 我想在列表中添加一个foreach字符串,并在数据库调用中添加一个 例如,如果列表中有2个字符串,则代码将等效为: return db.SA_Items .Include("first string in the list") .Include("second string in the list") .Where(x =&
List<string> includedTables
我想在列表中添加一个foreach字符串,并在数据库调用中添加一个
例如,如果列表中有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();
列表也可能为空
是否有可能以某种方式动态执行此操作
有人能给我一些指针吗?您可以在下面的stackoverflow链接中执行类似的操作,但是用字符串替换已添加的int索引:
当然,您可以通过几个步骤构建查询:
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
IQueryable查询=db.SA_项;
if(includedTables!=null)
query=includedTables.Aggregate(查询,(当前,包括)=>current.include(包括));
query=query.Where(x=>x.LastUpdated>LastUpdated)
.Where(x=>x.Active==true)
.OrderBy(x=>x.ItemID)
.跳过(偏移)
.采取(限制);
返回query.ToList();//具体化您的查询
你可以用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();
@Fabjan,必须急于加载相关实体,这是Include
method的建议。我收到错误:“无法将type”System.Data.Entity.Infrastructure.DbQuery“隐式转换为”System.Data.Entity.DbSet“。当前。Include(Include)部分上存在显式转换(是否缺少转换?):(这很有意义,使用IQueryable
类型而不是var
来保存查询。这应该可以解决问题。非常抱歉,现在它说“System.Linq.IQueryable”不包含“Include”的定义,并且找不到扩展方法“Include”接受类型为“System.Linq.IQueryable”的第一个参数(是否缺少using指令或程序集引用?“添加System.Data.Entity
命名空间
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();