在存储库中使用 Include() 方法 [英] Use Include() method in repository
本文介绍了在存储库中使用 Include() 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 EF 5 中有以下内容:
I have the following with EF 5:
var a = context.Posts.Include(x => x.Pack).Select(x => x.Pack.Id).ToList();
这有效.然后我尝试在我的通用存储库中复制它:
This works. Then I tried to replicate this in my generic repository:
public IQueryable<T> Include<T>(Expression<Func<T, Boolean>> criteria) where T : class
{
return _context.Set<T>().Include(criteria);
}
但在这种情况下,我无法执行以下操作:
But in this case I am not able to do the following:
var b = repository.Include<Post>(x => x.Pack).Select(x => x.Pack.Id).ToList();
我收到错误:
无法将类型 'Data.Entities.Pack' 隐式转换为 'bool'
Cannot implicitly convert type 'Data.Entities.Pack' to 'bool'
我该如何解决这个问题?
How can I solve this?
我应该在我的 Include() 方法中更改什么?
What should I change in my Include() method?
推荐答案
尝试:
改变
Expression<Func<T, Boolean>> criteria
到
Expression<Func<T, object>> criteria
要包含多个实体,您需要添加一个包含"扩展名:
To Include multiple entities, you need to add an "include" extension:
public static class IncludeExtension
{
public static IQueryable<TEntity> Include<TEntity>(this IDbSet<TEntity> dbSet,
params Expression<Func<TEntity, object>>[] includes)
where TEntity : class
{
IQueryable<TEntity> query = null;
foreach (var include in includes)
{
query = dbSet.Include(include);
}
return query == null ? dbSet : query;
}
}
然后你可以这样使用它:
Then you can use it like this:
repository.Include(x => x.Pack, x => x.Pack.Roles, ...).Select(x => x.Pack.Id).ToList();
只要确保repository"返回一个DbSet"对象.
Just make sure "repository" return a "DbSet" Object.
这篇关于在存储库中使用 Include() 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文