1
我有一個class
稱爲第同類型的的EntityFramework 5 CodeFirst兒童家長不更新/保存
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
添加到這樣一個已經存在的父:
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中工作,我做錯了什麼?
什麼總成讓我獲得了強類型的版本? – 2013-03-11 05:53:12
Nm,剛剛找到它'System.Data.Entity' – 2013-03-11 05:56:34