我有两个实体权限和访问权限
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); } /*...*/ }
AccessService.cs
GenericRepository<Access> accessRepo = new GenericRepository<Access>(); List<Access> accessList = accessRepo.Get(d => d.Name == accessName,null,"PermissionList").OrderBy(d => d.Id).ToList();
此代码过滤记录类型的“Access”,然后在Generic Repository中使用Include()方法和“PermissionList”参数.什么是包含(“PermissionList”)方法的工作?
它有什么作用? PermissionList是Access的一个属性,其元素类型为Permission.但我无法完全了解它的目标.
解决方法
它是为了热切地加载相关实体.
见Entity Framework Loading Related Entities.
当不使用Include()时,此查询:
using (var context = new YourContext()) { var access = context.Access.Single(a => a.ID == 42); }
将返回具有空PermissionList属性的Access实例.根据您的上下文的配置方式,此集合将保持为空(无延迟加载),或者一旦访问它就会延迟加载(foreach(access.PermissionList中的var权限){…}).
现在使用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”被急切加载,并且它似乎使用逗号分隔列表(例如“PermissionList,PermissionList.ChildPermissions”)支持多个Include().