asp.net 实体框架核心,包括来自子类的不同属性

mctunoxg  于 2023-03-31  发布在  .NET
关注(0)|答案(2)|浏览(143)

我的类和存储库的结构:

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属性。我如何包含子类的属性?

68bkxrlz

68bkxrlz1#

**更新:**从版本2.1开始,EF Core现在自然支持派生类型上的包含,通过lambda Include/ThenInclude重载或stringInclude重载中的cast或as运算符。
原始答案(EF Core 2.1之前):

当前不支持派生实体导航属性的即时加载。
作为解决方法,您可以使用EF Core文档Loading Related Data部分中解释的提前加载显式加载查询相关实体的组合:

var user = _users.Include(u => u.Role).SingleOrDefault(u => u.UserId == id);
var userRoleQuery = db.Entry(user).Reference(u => u.Role).Query();
if (user.Role is ManagerUserRole)
    userRoleQuery.OfType<ManagerUserRole>().Include(r => r.Groups).Load();
else if (user.Role is PersonUserRole)
    userRoleQuery.OfType<PersonUserRole>().Include(r => r.Group).Load();
return user;
yvt65v4c

yvt65v4c2#

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();

相关问题