加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 来自TPH继承中的子类型的LINQ .Include()属性

发布时间:2020-12-15 07:43:42 所属栏目:百科 来源:网络整理
导读:我在Entity Framework中使用每层次表(TPH)继承.现在我希望得到一个列表 – 在这个例子中 – 部门可以是子类型.我希望集合中的项目包含自己的自定义属性,而不仅仅是基本模型的属性. 我怎样才能做到这一点? public class Department{ public Department() { D
我在Entity Framework中使用每层次表(TPH)继承.现在我希望得到一个列表 – 在这个例子中 – 部门可以是子类型.我希望集合中的项目包含自己的自定义属性,而不仅仅是基本模型的属性.

我怎样才能做到这一点?

public class Department
{
    public Department()
    {
        DepartmentType = this.GetType.Name;
    }
    public int Id {get; set;}
    public string DepartmentType {get; set;}
}

public class Finance : Department
{
    public virtual Manager Manager {get; set;}
}

public class Sports : Department
{
    public virtual Coach Coach {get; set;}
}


// This obviously crashes instantly
// How can I include Manager if type is Finance and Coach if type is Sports?
context.Departments
        .Include(c => (c is Finance) ? c.Manager : null)
        .Include(c => (c is Sports) ? c.Coach : null);

我甚至试图返回IEnumerable< object>并为每个子类型添加一个多态方法,如下所示:

public class Sports : Department
{
    public Coach Coach {get; set;}

    public object Export()
    {
        return new 
        {
            this.Id,this.DepartmentType,this.Coach
        }
    }
}

然后做这样的事情:

context.Departments.Select(c => c.Export())

但这也不起作用.

期望的JSON用法

[
    { Id: 1,DepartmentType: "Finance",Manager: { Name: "John" } },{ Id: 2,Manager: { Name: "Harold" } },{ Id: 3,DepartmentType: "Sport",Coach: { Name: "Fred",SportType: "Soccer" } },{ Id: 4,Manager: { Name: "Hank" } },{ Id: 5,Coach: { Name: "Mark",SportType: "Football" } }
]

解决方法

通过这种方式,您可以找到财务和体育部门并包括他们的财产:
var financeDeparments = context.Departments.OfType<Finance>().Include(p => p.Manager).ToList();
var sportDepartments = context.Departments.OfType<Sports>().Include(p => p.Coach).ToList();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读