简体   繁体   中英

Return list of parents with the object

I am using entity framework and linq and I am trying to return an array of parents without using a for loop. Basically here is an example like the one I am facing (I can't give the real example but this is the same thing). There is a person and when I retrieve that person, I want to get an array of that person's ancestors (Male only). So I would return and array [father, grandfather, great-grandfather,...] until the "Father" property is null, or in other words we don't know who the person's father is. What would be the best way to do this with Entity Framework?

Here's an example:

class Person()
{
    public string Name { get; set; }
    public Guid FatherId { get; set; }
    public virtual Person Father { get; set; }
}

class PersonDto()
{
    public string Name { get; set; }
    public IEnumerable<PersonDto> Ancestors { get; set; }
}

How I would do this with a for loop is:

Person person = Context.People.Find(personId);
PersonDto personDto = person.ToDto();

Person father = person.Father;

while (father != null)
{
    personDto.Ancestors.Add(father.ToDto());
    father = father.Father;
}

Assuming that there is a foreign key on your person table that references the father (within the same table), and that you are using SQL Server for persistence, you would probably be best off using a stored procedure containing a common table expression to do this.

http://blogs.msdn.com/b/simonince/archive/2007/10/17/hierarchies-with-common-table-expressions.aspx

If you then use EF to run the SP, and set the import as returning a set of "Person", you should also find (as an added bonus) that the parents are actually set on the objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM