【问题标题】:Fluent NHibernate automappings with self-referenceFluent NHibernate 自动映射和自引用
【发布时间】:2010-09-24 12:52:55
【问题描述】:

我有一个看起来像这样的简单类...

public class Item {
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual int ParentId { get; set; }

    public virtual IList<Item> Children { get; private set; }

    public Item() {
        Children = new List<Item>();
    }
}

... 其中 Id 是主键,ParentId 是外键。当我运行此代码时,我得到无效的对象名称“ItemToItem”。异常,我不知道出了什么问题?我似乎 NHibernate 试图从名为 ItemToItem 的表或类似的表中进行选择?

【问题讨论】:

    标签: c# fluent-nhibernate


    【解决方案1】:

    正确的自我引用方式

    // Class
    public class Item 
    {    
        public virtual int Id { get; set; }    
        public virtual string Name { get; set; }    
        public virtual Item Parent { get; private set; }
        public virtual IList<Item> Children { get; set; }    
        public Item() {        
            Children = new List<Item>();    
        }
     }
    
     // Map
     References(x => x.Parent).Column("ParentId");
     HasMany(x => x.Children).Cascade.All().KeyColumn("ParentId");
    
     // Add Item
     session.Save(new Item { Description = "Electronics", 
                            Children = { 
                                    new Item { Description = "PS2" },
                                    new Item { Description = "XBox" }
                            }});  
    // Get Item
    var items =
              (from c in session.Linq<Item>()
                     where c.Parent == null
                     select c).ToList();   
    

    【讨论】:

    • 在设置数据库等时,我应该如何在 Fluently.Configure() 配置中使用这种映射?
    • 如果您想要没有父级的实体,您可以将 Nullable 添加到:References(x => x.Parent).Column("ParentId").Nullable()。
    【解决方案2】:

    是的。 fluent nhibernate 将其视为多对多关系。我不知道如何建立你想要的关系类型。你可能至少想建立一个成员:

    public virtual Item Parent{ get; set; }
    

    【讨论】:

    • 父项目运行良好,但我帖子中的异常仍然存在。
    猜你喜欢
    • 2012-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多