gpt4 book ai didi

entity-framework - 具有多个父属性、单个子集合的 EF6 自引用表

转载 作者:行者123 更新时间:2023-12-04 08:06:48 24 4
gpt4 key购买 nike

我有一个引用自身的表,但我正在努力获取所需的映射。我希望能够将 child 定义为具有特定人为母亲、父亲和/或监护人的人的集合。监护人可以是父亲或母亲。

我想要一个可浏览的人的树状 View ;用户可以展开一个人的节点以显示该人的所有 child ,而不管 child 的定义关系(母亲、父亲或监护人)。

public partial class Person
{
[Key]
public int ID { get; set; }

[StringLength(100)]
public string Name { get; set; }


public int? GuardianID { get; set; }

[Column("MotherID")]
public int? MotherID { get; set; }


[Column("FatherID")]
public int? FatherID { get; set; }

[ForeignKey("MotherID")]
public virtual tblPerson Mother { get; set; }

[ForeignKey("FatherID")]
public virtual tblPerson Father { get; set; }

[ForeignKey("GuardianID")]
public virtual tblPerson Guardian { get; set; }

[InverseProperty("Guardian")]
[InverseProperty("Father")]
[InverseProperty("Mother")]
public virtual IEnumerable<tblPerson> children { get; set; }
}

现在任何帮助将不胜感激,我的观点必须如下所示:
    @using Person_MVC.Models
@model IEnumerable<Person>
@{
IEnumerable<Person> children;
}

<ul>
@foreach (Person person in Model.OrderBy(p => p.PersonNumber))
{
<li id="Pnl_@Person.ID" data-jstree='{"type":"Person"}' data-Personkey="@Person.ID.ToString()">
@Person.Name
@{
PersonModel db = new PersonModel();
children = (from p in db.Persons where p.GuardianID == Person.ID || p.Father == Person.ID || p.MotherID == Person.ID select p).ToList();
}
@if (children != null && children.Count() > 0)
{
@Html.Partial("PersonTree", children)
}
</li>
}
</ul>

最佳答案

我想更好的解决方案是在您的模型中制作三个导航列表,并且可能有一种方法来加入对象以将所有儿子返回给您。

例如

public int? FatherId { get; set; }

public int? GrandFatherId { get; set; }

public int? MotherId { get; set; }

public virtual ICollection<Person> FatherForThose { get; set; }
public virtual Person Father { get; set; }

public virtual ICollection<Person> GrandFatherForThose { get; set; }
public virtual Person GrandFather { get; set; }

public virtual ICollection<Person> MotherForThose { get; set; }
public virtual Person Mother { get; set; }


public ICollection<Person> GetChildren()
{
var list = FatherForThose.Concat(MotherForThose).ToList();
foreach (var person in GrandFatherForThose)
{
if (list.All(i => i.Id != person.Id))
{
list.Add(person);

}
}
return list;
}

但是您应该始终注意将它们包含在您的查询中
例如
var grand = context.Persons.Include(x => x.FatherForThose)
.Include(x => x.GrandFatherForThose)
.Include(x => x.MotherForThose)
.FirstOrDefault(x => x.Id == 2);

var list = grand.GetChildren();

关于entity-framework - 具有多个父属性、单个子集合的 EF6 自引用表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30783561/

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