views:

285

answers:

2

I have a simple class that looks like this...

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

... where the Id is the primary key and ParentId is the foreign key. When I run this code I get Invalid object name 'ItemToItem'. exception and I can't figure out what's wrong? I seems like NHibernate tries to select from a table called ItemToItem or something like that?

A: 

Yes. fluent nhibernate is seeing this as a many-many relationship. I dont know off the top of my head how to create the type of relationship you want. you'll probably at least want to set up a member:

public virtual Item Parent{ get; set; }
JeffreyABecker
The parent item worked great but the exception from my post still exists.
Marcus
A: 

Correct way to self reference

// 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();
ashraf
How should I use this kind of mappings within the Fluently.Configure() configuration when I setup my database and so on?
Marcus
I used Override<Item> and it seems to work.
Marcus