我正在编写一个函数,允许用户从数据库(底层提供程序是EF)获得可查询的设备列表。但我希望允许它们指定自己的包含,但如果它们总是包含Capabilites
的默认包含,我该怎么做呢?
public IQueryable<Device> GetAllDevices(params Expression<Func<Device, object>>[] includes)
{
// I really want to do something like includes.Add(d => d.Capabilities)
// (I know the above code wouldnt work, but illustrates what I want)
var newIncludes = includes /*(and somehow)*/ d => d.Capabilities,
return this.Repository.GetAll(newIncludes);
}
这是在我的存储库类上使用的函数,它聚合了在其中发送的包含。我似乎不知道如何在上面的函数
中添加一个默认的include。public IQueryable<T> GetAll(params Expression<Func<T, object>>[] includes)
{
IQueryable<T> query = this.dbset;
if (includes != null)
{
query = includes.Aggregate(query, (current, include) => current.Include(include));
}
return query;
}
不使用相同的Include()
两次没有特定的限制。第二个被忽略。
public IQueryable<Device> GetAllDevices(params Expression<Func<Device, object>>[] includes)
{
return this.Repository.GetAll(includes).Include(x => x.Capabilities);
}
这将始终是Include(x => x.Capabilities)
。
includes
为空),则不希望包含Capabilities
:
public IQueryable<Device> GetAllDevices(params Expression<Func<Device, object>>[] includes)
{
IQueryable<Device> query = this.Repository.GetAll(includes);
if (includes != null && includes.Length != 0)
{
query = query.Include(x => x.Capabilities);
}
return query;
}
你可以链"包括()其中包括()……":
(IQueryable<T>).Include("Something").Include("SomethingElse");
你可以使用它,并在"includes"数组上循环,这样就可以实现你的函数:
IQueryable<T> example = (some IQueryable<T>).Include(Capabilities);
foreach (include in includes)
example.Include(include);
返回DbSet其中(你的情况)其中包括(string.Join("。",包括)).FirstOrDefault ();