1

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次のように、既存の親に新しい子を追加しようとしています。

    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

ただし、次のように、parent をロードするSectionと、Childrenプロパティは常にCount0 になります。

    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 で機能しないことに非常に不満を感じています。何が間違っているのでしょうか?

4

1 に答える 1

2

Entity Frameworkは、関連するエンティティを熱心にロードしません。子を含めるように強制してみてください。

var model = FactoryTools.Factory.PdfSections.Include("Children").FirstOrDefault(x => x.Id == sectionId);

ラムダを渡すことができる強い型のオーバーロードもあります。

var model = FactoryTools.Factory.PdfSections.Include(s => s.Children).FirstOrDefault(x => x.Id == sectionId);
于 2013-03-11T04:47:56.077 に答える