gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:36:23 26 4
gpt4 key购买 nike

我在 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, DepartmentType: "Finance", Manager: { Name: "Harold" } },
{ Id: 3, DepartmentType: "Sport", Coach: { Name: "Fred", SportType: "Soccer" } },
{ Id: 4, DepartmentType: "Finance", Manager: { Name: "Hank" } },
{ Id: 5, DepartmentType: "Sport", 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();

关于c# - LINQ .Include() 来自 TPH 继承中子类型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27623637/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com