无法映射 NHibernate



我正在使用NHibernate。这是员工类

public class Employee
{
    public virtual int Id { get; protected set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual Store Store { get; set; }
}

这是存储类:

public class Store
{
    public virtual int Id { get; protected set; }
    public virtual string Name { get; set; }
    public virtual IList<Employee> Staff { get; set; }
    public Store()
    {
      Staff = new List<Employee>();
    }
}

以下是映射类。员工地图:

public class EmployeeMap : ClassMap<Employee>
{
    public EmployeeMap ()
    {
        Id(x => x.Id);
        Map(x => x.FirstName);
        Map(x => x.LastName);
        References(x => x.Store);
    }
}

店铺地图:

public class StoreMap:ClassMap<Store>
{
    public StoreMap() 
    {
        Id(x => x.Id);
        Map(x => x.Name);
        HasMany(x => x.Staff);
        // HasManyToMany(x => x.Products).Cascade.All();
        //.Table("StoreProduct");
    }
}

当我运行此代码时:

using (session.BeginTransaction())
{
    var stores = session.CreateCriteria(typeof(Store)).List<Store>();
    //for (int i=0; i<stores.Count;)
    //{
    //    Response.Write(st
    //}
    foreach (var item in stores)
    {
        Response.Write(item.Staff.ToList());
    }
}

我收到以下错误:

无法初始化集合:[测试。Models.Store.Staff#1][SQL: 选择"staff0_"。Store_id Store4_1_,staff0_。Id 作为 Id1_,staff0_。编号 正如Id0_0_,staff0_。姓氏为LastName0_0_,staff0_。名字为 FirstName0_0_,staff0_。Store_id 作为 Store4_0_0_ 来自 [员工] staff0_ 哪里staff0_。Store_id=?

你的代码对我来说似乎很好用。但是我从头开始生成一个空方案,不知道您是否可能缺少某些内容,或者是否正确设置了id引用。

如果未为 staff->Store 指定引用 Id 列,它将使用Sore_id,如查询文本所示。此列是否存在?

无论如何,如果它仍然不适合您,请尝试为您的HasMany(x => x.Staff);映射显式定义.KeyColumn的名称

:编辑:

您需要更改商店地图以具有HasMany(x => x.Staff).KeyColumn("store");

并且您需要更改员工地图以具有References(x => x.Store).Columns("store");

以便双方都链接到同一参考列...

最新更新