什么是Include()方法在Entity Framework中的工作

时间:2015-01-12 19:51:09

标签: c# asp.net-mvc linq entity-framework

我有两个实体权限和访问权限

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; }

    [NotMapped]
    public bool HasChildren { get; set; }

    [NotMapped]
    public List<Permission> ChildPermissions { get; set; }
}

我还有GenericRepository类来过滤我数据库中的记录。

GenericRepository.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);
            }
        /*...*/
        }

我在Access Service类中调用此方法

AccessService.cs

GenericRepository<Access> accessRepo = new GenericRepository<Access>();
List<Access> accessList = accessRepo.Get(d => d.Name == accessName, null, "PermissionList").OrderBy(d => d.Id).ToList();

此代码过滤&#34; Access&#34;的记录类型。然后使用Include()方法和&#34; PermissionList&#34;通用存储库中的参数。什么包括(&#34; PermissionList&#34;)方法的工作? 它有什么作用? PermissionList是Access的一个属性,其元素类型为Permission。但我无法完全了解其目标。

1 个答案:

答案 0 :(得分:13)

这是为了热切地加载相关实体。

请参阅Entity Framework Loading Related Entities

当不使用Include()时,此查询:

using (var context = new YourContext())
{
    var access = context.Access.Single(a => a.ID == 42);    
}

将返回具有空Access属性的PermissionList实例。根据您的上下文的配置方式,此集合将保持为空(不延迟加载),或者一旦访问它就会延迟加载(foreach (var permission in access.PermissionList) { ... })。

现在使用Include()

using (var context = new YourContext())
{
    var access = context.Access.Include(a => a.PermissionList)
                               .Single(a => a.ID == 42);    
}

查询将被写为连接,为您加载所有相关权限。

Include()扩展方法也有一个字符串重载,您的存储库代码正在调用:

query = query.Include(includeProperty);

这会导致您的案例"PermissionList"急切加载,并且似乎支持多个Include()使用以逗号分隔的列表(例如"PermissionList,PermissionList.ChildPermissions")。