實體框架核心包含子類的不同屬性

asp.net c# entity-framework-core

我的類和存儲庫的結構:

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 Type轉換為實際的PersonUserRole類型以包含Group / Groups屬性。如何包含子類的屬性?

一般承認的答案

更新:從版本2.1開始,EF Core現在通過ThenIncludeas運算符內部的lambda Include / ThenInclude重載或string Include重載來自然支持派生類型的 Include

原始答案(前EF Core 2.1):

目前不支持急切加載派生實體導航屬性。

作為一種解決方法,您可以使用EF Core文檔的“ 加載相關數據”部分中說明的Eager加載顯式加載查詢相關實體的組合:

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;

熱門答案

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


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow