c# - 具有自引用功能的 Fluent NHibernate 自动映射

标签 c# fluent-nhibernate

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

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 或类似名称的表中进行选择?

最佳答案

自引用的正确方法

// 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();   

关于c# - 具有自引用功能的 Fluent NHibernate 自动映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1547956/

相关文章:

c# - 在 C# 中向类添加静态方法,我知道你不需要替代方法

c# - Fluent NHibernate 正在创建一个额外的外键列...为什么?

asp.net-mvc - 在 Asp.Net MVC 应用程序中使用 Structuremap 将 ISession 注入(inject)我的存储库

sqlite - 使用 SQLite In Memory 配置测试 NHibernate 时,如何创建另一个数据库?

C# 添加 string + null 不会抛出错误?

c# - DbEntityValidationException - 必填字段为空

c# - 如何在 ASP.Net MVC 3 中重定向到 ActionResult 中的路由

c# - Windows 8 应用程序 C# 'string' 不包含 'Copy' 的定义

asp.net-mvc - 当您的 View 模型没有与域模型一样多的字段时,您如何忽略/保留 MVC 中的值?

nhibernate - 支持部分版本的 .NET 数据库迁移