1

我需要使用.NHibernate

这是我想出的:

public class CategoryMap : ClassMap<Category>
{
    public CategoryMap()
    {
        Id(x => x.Id);
        Map(x => x.AppId);
        Map(x => x.Title);
        Map(x => x.MaxDepth).Default("3");
        Map(x => x.IsActive);
        References(x => x.Parent).LazyLoad().Column("ParentId");

        HasMany(x => x.ChildrenNodes)
            .LazyLoad()
            .KeyColumn("ParentId")
            .Cascade.All();

        Table("Category");
    }
}

public class Category : Node
{
    public virtual string AppId { get; set; }
    public override string Title { get; set; }
    public override int MaxDepth { get; set; }
    public virtual Category Parent { get; set; }
    public virtual IList<Category> ChildrenNodes { get; set; }
    public virtual bool IsActive { get; set; }
}

public abstract class Node
{
    public virtual long Id { get; set; }
    public abstract string Title { get; set; }
    public abstract int MaxDepth { get; set; }
}

这是我的测试代码:

[Test]
    public void CreateTableInDb()
    {

        using (var db = new FileDatabase(DbFileLocation, true))
        {
            var categoryMenu = new Category
            {
                AppId = "1",
                MaxDepth = 3,
                IsActive = true,
                Title = "Services"
            };

            db.Create(categoryMenu);


            categoryMenu.ChildrenNodes = new List<Category>
            {
                new Category
                {
                    Title = "SubService-Level1",
                    Parent = categoryMenu,
                }
            };

            db.Update(categoryMenu);
        }
    }

当我查看它正在创建的表格时,我只有一行,有空ParentId列。

我该如何解决它以及我做错了什么?

4

1 回答 1

0
  • 首先你会错过.Inverse()hasman。就目前而言,它将保存并更新 parentId 两次
  • 所有集合都应该是只读的。NHibernate 将用您丢弃的跟踪和延迟加载集合替换它们。将代码更改为

    public class Category : Node
    {
        public Category()
        {
            // best practice so that nobody has to null check the collection
            ChildrenNodes = new List<Category>();
        }
        public virtual IList<Category> ChildrenNodes { get; private set; }
    
        public void Add(Category subcategory)
        {
            subcategory.Parent = this;
            ChildrenNodes.Add(subcategory);
        }
    }
    
    // in testcode
    categoryMenu.Add(new Category { Title = "SubService-Level1" });
    
于 2013-03-22T12:40:52.197 回答