0
votes

I am using NHibernate. This is the employee class

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; }
}

This is the store class:

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

The following are the mapping classes. Employee Map:

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

Store Map:

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");
    }
}

When I run this code:

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

I receive the following error:

could not initialize a collection: [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_ WHERE staff0_.Store_id=?]

1

1 Answers

0
votes

You code seems to work fine for me. But I'm generating an empty scheme from scratch, don't know if you are maybe missing something or if the id references are set correctly.

If you do not specify the reference Id column for staff->Store it uses Sore_id as you can see in your query text. Does this column exist?

Anyways, if it is still not working for you, try to explicitly define a name for the .KeyColumn for your HasMany(x => x.Staff); mapping

:edit:

You need to change StoreMap to have HasMany(x => x.Staff).KeyColumn("store");

And you need to change EmployeeMap to have References(x => x.Store).Columns("store");

So that both sides link to the same reference column...