![](/img/trans.png)
[英]EntityFramework - Table per Type (TPT) Inheritance and Mapping Relationships with CodeFirst
[英]EntityFramework 5 CodeFirst Child Parent of the Same Type Not Updating/Saving
我有一class
public class Section
{
public Section() { construct(0); }
public Section(int order) { construct(order); }
private void construct(int order)
{
Children = new List<Section>();
Fields = new List<XfaField>();
Hint = new Hint();
Order = order;
}
[Key]
public int Id { get; set; }
public int FormId { get; set; }
public string Name { get; set; }
[InverseProperty("Parent")]
public List<Section> Children { get; set; }
public List<XfaField> Fields { get; set; }
public Section Parent { get; set; }
public Hint Hint { get; set; }
public int Order { get; private set; }
#region Methods
public void AddNewChild()
{
AddChild(new Section
{
Name = "New Child Section",
FormId = FormId,
});
}
private void AddChild(Section child)
{
child.Parent = this;
if (Children == null) Children = new List<Section>();
int maxOrder = -1;
if(Children.Count() > 0) maxOrder = Children.Max(x => x.Order);
child.Order = ++maxOrder;
Children.Add(child);
FactoryTools.Factory.PdfSections.Add(child);
}
// Other methods here
#endregion
}
我試圖像這樣將新的子Section
添加到已存在的父Section
中:
private void AddChildSection()
{
var parent = FactoryTools.Factory.PdfSections.FirstOrDefault(x => x.Id == ParentId);
if (parent == null) throw new Exception("Unable to create child because parent with Id " + ParentId.ToString() + " doesn't exist.");
parent.AddNewChild();
FactoryTools.Factory.SaveChanges();
}
在查看數據庫時,我看到已添加了新行,例如:
Id Name Parent_Id Hint_Id FormId Order
19 New Child Section 1 27 1 0
但是,當我加載父Section
, Children
屬性始終為Count
0,如下所示:
public ActionResult EditSection(int formId, int sectionId)
{
var model = FactoryTools.Factory.PdfSections.FirstOrDefault(x => x.Id == sectionId);
if (model == null || model.FormId != formId) model = new Section();
//model.Children = FactoryTools.Factory.PdfSections.Where(x => x.Parent.Id == sectionId).ToList();
return PartialView(model);
}
當然,當我手動添加子項時,它們就在那里了(在上面的代碼中,通過取消注釋模型model.Children = ...
行)
我已經習慣了NHibernate的工作方式,因此對上面看似簡單的任務在EntityFramework中無法正常工作感到沮喪,我在做什么錯?
實體框架不會急於加載相關實體。 嘗試強迫它包括子代:
var model = FactoryTools.Factory.PdfSections.Include("Children").FirstOrDefault(x => x.Id == sectionId);
還有一個強類型的重載,您可以將lambda傳遞給該重載:
var model = FactoryTools.Factory.PdfSections.Include(s => s.Children).FirstOrDefault(x => x.Id == sectionId);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.