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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With