我的类和存储库的结构:
public class Group{
//fields
}
public class User{
public UserRole Role {get;set;}
}
public abstract class UserRole{
//fields
}
public class PersonUserRole:UserRole{
public Group Group {get;set;}
}
public class ManagerUserRole:UserRole{
public IList<Group> Groups {get;set;}
}
我遇到问题的一个例子:
public class UserRepository:IUserRepository{
private readonly ApplicationDbContext _dbContext;
private readonly DbSet<User> _users;
public UserRepository(ApplicationDbContext dbcontext)
{
_dbContext = dbcontext;
_users = _dbContext.DomainUsers;
}
public User GetBy(int id)
{
User type = _users.Include(u => u.Role)
.SingleOrDefault(c => c.UserId == id);
if (typeof(PersonUserRole) == type.Role.GetType())
{
return
_users.Include(u => u.Role)
.ThenInclude(r => (r as PersonUserRole).Groep)
.SingleOrDefault(c => c.UserId == id);
}
else
{
return _users.Include(u => u.Role)
.ThenInclude(r => (r as ManagerUserRole).Groups)
.SingleOrDefault(c => c.UserId == id);
}
}
}
我收到以下错误消息:
消息&#34;属性表达式&#39; r =&gt; (r As PersonUserRole).Group&#39;不是 有效。表达式应代表属性访问权限:&#39; t =&gt; t.MyProperty&#39;
我似乎无法将UserRole
类型转换为实际的PersonUserRole
类型以包含“组/组”属性。如何包含子类的属性?
答案 0 :(得分:4)
更新:从版本2.1开始,EF Core现在自然支持Include on derived types通过强制转换或lambda as
/ {{1内的Include
运算符}重载或ThenInclude
string
重载。
原始答案(前EF Core 2.1):
目前不支持加载派生实体导航属性。
作为一种解决方法,您可以使用Loading Related Data中解释的预先加载,显式加载和查询相关实体的组合EF Core文档的一部分:
Include
答案 1 :(得分:2)
EntityFramework有一个未解决的问题,与您的问题非常相似:https://github.com/aspnet/EntityFramework/issues/3910
也许你可以尝试他们的建议,但我无法尝试它是否有效:
var o = context.Set<Order>() .Where(o => o.Id == 1234) .Single(); context.Set<GroupPosition>() .Where(x => x.Order == o) .Include(x => x.GroupType) .Load(); context.Set<SalesPosition>() .Where(x => x.Order == o) .Include(x => x.Group) .Load();