在使用存储库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();
我得到的错误:
I get the error:
无法隐式转换类型'Data.Entities.Pack'到'布尔
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();
只要确保库返回DbSet对象。
Just make sure "repository" return a "DbSet" Object.
这篇关于在使用存储库include()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文