我的类和存储库的结构:
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);
}
}
}
我收到以下错误消息:
消息“属性表达式'r =〉(r As PersonUserRole).Group'无效。表达式应表示属性访问:'t =〉t.MyProperty'
似乎我不能将我的UserRole
类型转换为实际的PersonUserRole
类型以包含Group/Groups属性。我如何包含子类的属性?
2条答案
按热度按时间68bkxrlz1#
**更新:**从版本2.1开始,EF Core现在自然支持派生类型上的包含,通过lambda
Include
/ThenInclude
重载或string
Include
重载中的cast或as
运算符。原始答案(EF Core 2.1之前):
当前不支持派生实体导航属性的即时加载。
作为解决方法,您可以使用EF Core文档Loading Related Data部分中解释的提前加载、显式加载和查询相关实体的组合:
yvt65v4c2#
EntityFramework有一个开放的问题,与您的问题完全相同:https://github.com/aspnet/EntityFramework/issues/3910
也许你可以试试他们建议的,但我不能尝试是否有效: