Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fluent NHibernate automappings with self-reference

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?

like image 318
marcus Avatar asked Oct 10 '09 13:10

marcus


1 Answers

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();   
like image 59
ashraf Avatar answered Oct 29 '22 22:10

ashraf