简体   繁体   中英

Entity Framework Load Child With Parent

public class Parent {
    public int Id { get; set; }
    public string Name { get; set; }
    public Child ChildField { get; set; }
}

public class Child {
    public int Id { get; set; }
    public int Age { get; set; }
    public int ParentId { get; set; }
}

public class MyDbContext : DbContext {
    public DbSet<Parent> Parents { get; set; }
    public DbSet<Child> Childs { get; set; }
}

DB Rows:

parent_id | name
1           "Parent 1"
2           "Parent 2"

Child Rows
child_id | age | parent_id
3           15      1
4           21      2

I have a method that looks like this:

public Parent Get(int parentId) {
    var result = this.dbContext.Parents
         .Join(
             this.dbContext.Childs,
             p => p.Id,
             c => c.ParentId,
             (p, c) => new { Parent = p, Child = c })
             .AsNoTracking().Where(m => m.Parent.Id == parentId)
             .FirstOrDefault()

    result.Parent.Child = result.Child;
    return result.Parent;
}

This is currently working for me, but I'd like to not have to manually assign the child to the parent after this join.

  1. Is there a better way to do this? I would like to use this same style of syntax.
  2. How can I accomplish this without having to manually assign the Child to the Parent?

Thanks!

The including...

FatherRepository.All().Including(x => x.Childs, x => x.Childs.Select(y => y.ChildChild));

Father class...

public class Father
{
    public int Id { get; set; }

    #region Navigations Properties
    public virtual List<Child> Childs { get; set; }
    #endregion
}

Child class...

public class Child
{
    public int Id { get; set; }
    public int ChildChildId { get; set; }
    public int FatherId { get; set; }

    #region Navigations Properties
    public virtual Father Father { get; set; }
    public virtual ChildChild ChildChild { get; set; }
    #endregion

}

ChildChild class...

public class ChildChild
{
    public int Id { get; set; }
}

Just write :

var result = this.dbContext.Parents.Where(m => m.Parent.Id == parentId)
     .Include(p=>p.Child).FirstOrDefault()

result will contains corresponding childs

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