我有两个有一对多关系的班级。
名称:Access
和Permission
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
答案 0 :(得分:-1)
试试这个:
public virtual List<Permission> PermissionList { get; set; }
var query= context.Entity.Include(d => d.PermissionList);
您可以查看说明here