实体框架核心包含与子类不同的属性

实体框架核心包含与子类不同的属性

本文介绍了实体框架核心包含与子类不同的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的课程和存储库的结构:

The structure of my classes and repository:

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

我收到以下错误消息:

似乎我无法投射 UserRole 类型键入为实际的 PersonUserRole 类型,以包含Group / Groups属性。如何包含子类的属性? / p>

It seems like I cannot cast my UserRole Type to the actual PersonUserRole Type to include the Group/Groups property. How can I include the properties of the subclasses?

推荐答案

更新:从版本2.1开始,现在自然可以通过任一强制转换得到EF Core支持或lambda Include / ThenInclude 中的 as 运算符重载或字符串 包含

Update: Starting with version 2.1, Include on derived types is now naturally supported by EF Core via either cast or as operator inside lambda Include / ThenInclude overloads or string Include overload.

原始答案(EF Core 2.1之前的版本):

目前急切不支持加载派生的实体导航属性。

Currently eager loading of derived entity navigation properties is not supported.

作为解决方法,可以结合使用急切加载显式加载查询相关实体在部分:

As a workaround you can use a combination of Eager loading, Explicit loading and Querying related entities explained in the Loading Related Data section of the EF Core documentation:

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;

这篇关于实体框架核心包含与子类不同的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 14:52