实体框架使用父项加载子项

时间:2014-11-07 02:43:25

标签: c# entity-framework

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

我有一个看起来像这样的方法:

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;
}

目前这对我有用,但我不想在这次加入后手动将孩子分配给父母。

  1. 有更好的方法吗?我想使用相同的语法风格。
  2. 如何在不必手动将Child分配给Parent的情况下完成此操作?
  3. 谢谢!

2 个答案:

答案 0 :(得分:1)

包括......

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

父班......

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

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

儿童班......

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班级......

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

答案 1 :(得分:0)

只需写下:

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

结果将包含相应的孩子