相关疑难解决方法(0)

实体框架linq查询Include()多个子实体

这可能是一个非常重要的问题,但是当编写跨越三个级别(或更多)的查询时,包含多个子实体的好方法是什么?

即我有4个表:Company,Employee,Employee_CarEmployee_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

linq entity-framework lazy-loading

167
推荐指数
4
解决办法
26万
查看次数

EntityFramework包含(Eager Load)虚拟属性的虚拟属性

想象一下,我们有三个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].Specificationsnull,我们怎样才能让它急切加载集合的子集合呢?

PS:我尝试删除virtual关键字进行测试(我不想删除它),但它也没有用.

c# asp.net asp.net-mvc entity-framework

7
推荐指数
2
解决办法
1951
查看次数

实体框架5.多个包含.这可能吗?

我试图在我的存储库中创建一个多包含方法,使用如下:

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;

我可以在不将我的存储库方法变为静态的情况下完成这项工

谢谢,

米格尔

entity-framework

5
推荐指数
1
解决办法
8762
查看次数

使用 theninclude() 方法进行急切加载的通用存储库?

这是我的通用存储库:

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() 来解决这个问题,但我不知道如何将它应用到通用存储库中。

任何帮助真的很感激。

谢谢

c# asp.net entity-framework eager-loading

5
推荐指数
1
解决办法
3155
查看次数