views:

35

answers:

1

I seem to have major problems getting a one to many relationship to work in nhibernate

and my classes are

public class Kitten
{
    public virtual int? Id { get; set; }
    public virtual String Name { get; set; }
}

public class Product 
{
    public Product()
    {
        Kittehs = new List<Kitten>();
    }
    public virtual int? ProductId { get; set; }
    public virtual string ProductName { get; set; }
    public virtual UnitOfMeasure UOM { get; set; }
    public virtual IList<Kitten> Kittehs { get; set; }
}

And here's my a snippet program:

First:

 public class ProductRepository
 // snip
    public void Save(Product saveObj)
    {
        using (var session = GetSession())
        {               
            using(var trans = session.BeginTransaction())   
            {
                session.SaveOrUpdate(saveObj);
                trans.Commit();
            }
        }
    }

and then the calling code:

        var pNew = new Product { ProductName = "Canned Salmon" ,UOM = uomBottle};        
        var tiddles = new Kitten() {Name = "Tiddles"};
        pNew.Kittehs.Add(tiddles);
        productRepository.Save(pNew); //ERROR here

When I call productRepository.Save

I get

{"The type NHibernate.Collection.Generic.PersistentGenericSet1[Acme.Model.Kitten] can not be assigned to a property of type System.Collections.Generic.IList1[Acme.Model.Kitten] setter of Acme.Model.Product.Kittehs"}

so I'm assuming the mapping is wrong somehow but I can't see where.

+2  A: 

Well... you have a Set and then a List for Acme.Model.Kitten... Try to look at your mapping files.

You're using public virtual IList<Kitten> Kittehs { get; set; } in your Product class but inside your mapping this same property is mapped to a Set.

Bag maps to IList

Leniel Macaferi
what should it be? A bag?
John Nolan
Yes, a Bag... More about it here: http://codebetter.com/blogs/karlseguin/archive/2008/01/02/foundations-of-programming-part-6-nhibernate.aspx
Leniel Macaferi