Fluent NHibernate automappings with self-reference

2020-06-04 03:55发布

问题:

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?

回答1:

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


回答2:

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