在我的Web API
服务中使用带有EF6
的generic-repository / uow模式,我需要返回嵌套的导航属性。模型A具有模型B,模型B具有模型C等。像这样:
public class A
{
public int SomeID { get; set; }
public ICollection<B> Bs { get; set; }
}
public class B
{
public int SomeID { get; set; }
public ICollection<C> Cs { get; set; }
}
我可以在A中获得B,但B中的C是空的。这就是我的做法:
// GENERIC REPOSITORY
public IQueryable<TEntity> Get(params Expression<Func<TEntity, object>>[] includes)
{
IQueryable<TEntity> query = _dbSet;
if (includes != null)
{
foreach (var include in includes)
query = query.Include(include);
}
return query;
}
// FROM THE "A" CONTROLLER
public HttpResponseMessage Get()
{
HttpResponseMessage response;
var results = _unitOfWork.A_Repository.Get(s => s.Bs);
if (results == null)
{
response = new HttpResponseMessage(HttpStatusCode.NotFound);
}
else
{
response = Request.CreateResponse(HttpStatusCode.OK, results);
}
return response;
}
我不知道如何从A控制器传递额外的lambdas来获取B中的Cs。我可以看到如何在不使用通用存储库的情况下执行此操作。我也愿意使用OData,但无法弄清楚如何在Web API中使用此模式来实现它
我也尝试过使用DbContext方法而失败了:
public class MyContext : DbContext
{
public DbSet<A> As { get; set; }
public DbSet<B> Bs { get; set; }
public DbSet<C> Cs { get; set; }
public MyContext()
: base("MyDBContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<B>().HasRequired(i => i.C);
Bs.Include(i => i.C);
}
}
答案 0 :(得分:5)
您可以使用单个Include
电话执行此操作。
_context.A_Repository // where to get from
.Include(a => a.Bs.Select(b => b.Cs.Ds.Es)) // what to include
.Where(a => a.IsCool == true) // how to filter
.ToList(); // materialize result