C# 实体框架用父对象加载子对象
这目前对我有效,但我不想在加入后手动将子项分配给父项C# 实体框架用父对象加载子对象,c#,entity-framework,C#,Entity Framework,这目前对我有效,但我不想在加入后手动将子项分配给父项 有更好的方法吗?我想使用同样的语法风格 如何在不必手动将子对象分配给父对象的情况下完成此操作 谢谢 只要写: public Parent Get(int parentId) { var result = this.dbContext.Parents .Join( this.dbContext.Childs, p => p.Id, c
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;
}
结果将包含相应的child包括
var result = this.dbContext.Parents.Where(m => m.Parent.Id == parentId)
.Include(p=>p.Child).FirstOrDefault()
父亲班
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
}
我本来是这样做的,但是我得到了一个错误“无效列Child_Id”。。。父表中不存在子表的主键。父项的主键作为外键存在于子表中。是否可以尝试添加
[ForeignKey(“ChildField”)]\n public int?Child_Id{get;set;}
beforepublic Child字段{get;set;}
它不是先编码的。
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
}
public class ChildChild
{
public int Id { get; set; }
}