这可能是一个非常重要的问题,但是当编写跨越三个级别(或更多)的查询时,包含多个子实体的好方法是什么?
即我有4个表:Company,Employee,Employee_Car和Employee_Country
公司与员工有1:m的关系.
Employee与Employee_Car和Employee_Country都有1:m的关系.
如果我想编写一个返回所有4个表中数据的查询,我目前正在编写:
Company company = context.Companies
.Include("Employee.Employee_Car")
.Include("Employee.Employee_Country")
.FirstOrDefault(c => c.Id == companyID);
Run Code Online (Sandbox Code Playgroud)
必须有一个更优雅的方式!这是冗长的,并产生可怕的SQL
我在VS 2010中使用EF4
想象一下,我们有三个Dbset如下:
Category
{
...
public virtual ICollection<Item> Items {get; set;}
...
}
Item
{
...
public virtual ICollection<Specification> Specifications{get; set;}
...
}
Specification
{
...
}
Run Code Online (Sandbox Code Playgroud)
对于急切加载,我使用它像这样:
Category cat = db.Categories.Include(c=> c.Items).FirstOrDefault(c=> c.Id == 1);
Run Code Online (Sandbox Code Playgroud)
但现在的问题是
cat.Items[0].Specifications是null,我们怎样才能让它急切加载集合的子集合呢?
PS:我尝试删除virtual关键字进行测试(我不想删除它),但它也没有用.
我试图在我的存储库中创建一个多包含方法,使用如下:
repository.Include<Post>(x => x.Images, x => x.Tags).First(x => x.Id == 1)
Run Code Online (Sandbox Code Playgroud)
我尝试了一些东西:
public IQueryable<T> Include<T>(params Expression<Func<T, Object>>[] paths) where T : class {
return paths.Aggregate(_context.Set<T>(), (x, path) => x.Include(path));
} // Include
Run Code Online (Sandbox Code Playgroud)
但我得到错误:
无法将类型'System.Linq.IQueryable'隐式转换为'System.Data.Entity.DbSet'.
请注意,原始包含如下:
public static IQueryable Include(这个IQueryable源,Expression> path)其中T:class;
我可以在不将我的存储库方法变为静态的情况下完成这项工
谢谢,
米格尔
这是我的通用存储库:
public class Repository<T> : IRepository<T> where T : BaseEntity
{
private DbContext _dbContext { get; set; }
private DbSet<T> _dbSet { get; set; }
public Repository(DbContext context)
{
this._dbContext = context;
this._dbSet = context.Set<T>();
}
public IQueryable<T> GetAll(params Expression<Func<T, object>>[] includes)
{
IQueryable<T> currentSet = this._dbSet;
foreach (var item in includes)
{
currentSet = currentSet.Include(item);
}
return currentSet;
}
public T Get(Expression<Func<T, bool>> predicated,
params Expression<Func<T, object>>[] includes)
=> this.GetAll(includes).Where(predicated).FirstOrDefault();
}
Run Code Online (Sandbox Code Playgroud)
问题是当我使用急切加载来加载问题(包括其答案)时,我无法查询答案的投票。
我发现我收到了这个错误,因为我正在加载一个问题,包括它的答案,并再次包括答案的投票。所以我尝试使用 thenInclude() 来解决这个问题,但我不知道如何将它应用到通用存储库中。
任何帮助真的很感激。
谢谢