无法映射NHibernate

时间:2013-12-25 16:34:22

标签: c# 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());
    }
}

我收到以下错误:

  

无法初始化集合:[test.Models.Store.Staff#1] [SQL:   SELECT staff0_.Store_id as Store4_1_,staff0_.Id as Id1_,staff0_.Id   as Id0_0_,staff0_.LastName as LastName0_0_,staff0_.FirstName as   FirstName0_0_,staff0_.Store_id as Store4_0_0_ FROM [Employee] staff0_   在哪里staff0_.Store_id =?]

1 个答案:

答案 0 :(得分:0)

你的代码似乎对我很好。但我从头开始生成一个空方案,不知道你是否遗漏了某些东西,或者是否正确设置了id引用。

如果您没有为员工指定参考ID列 - &gt;存储它会使用Sore_id,您可以在查询文本中看到。这个专栏是否存在?

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

:编辑:

您需要将StoreMap更改为HasMany(x => x.Staff).KeyColumn("store");

您需要将EmployeeMap更改为References(x => x.Store).Columns("store");

这样双方都会链接到同一个参考栏......