包含方法无法加载

时间:2015-02-06 09:51:04

标签: c# asp.net-mvc entity-framework lazy-loading eager-loading

我有两个有一对多关系的班级。

名称:AccessPermission

Access.cs

public class Access
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Permission> PermissionList { get; set; }
}

Permission.cs

public class Permission
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int ParentId { get; set; }
}

我在上下文类

中建立了一对多的关系

MyContext.cs

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<IncludeMetadataConvention>(); // turn off code-first db initialization

    modelBuilder.Entity<Access>().HasMany<Permission>(o => o.PermissionList).WithOptional();
    modelBuilder.Entity<Access>().HasMany(o => o.PermissionList).WithMany();
    base.OnModelCreating(modelBuilder);
}

我想列出所有Access es Permission s但是当我尝试从实体框架中获取Access时,Permission s无法加载。但是我在我的存储库中使用Include方法。

MyRepository.cs

public virtual IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "", bool tracking = true)
    {
        IQueryable<TEntity> query = dbSet;


        if (filter != null)
        {
            query = query.Where(filter);
        }

        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);

        }

        if (orderBy != null)
        {
            if (!tracking)
            {
                return orderBy(query).AsNoTracking<TEntity>().ToList();
            }
            else
            {
                return orderBy(query).ToList();
            }
        }
        else
        {
            if (!tracking)
            {
                return query.AsNoTracking<TEntity>().ToList();
            }
            else
            {
                return query.ToList();
            }
        }
    }

我不明白为什么PermissionList无法热切地加载到Access

1 个答案:

答案 0 :(得分:-1)

试试这个:

public virtual List<Permission> PermissionList { get; set; }

var query= context.Entity.Include(d => d.PermissionList);

您可以查看说明here