本文介绍了功能NHibernate automappings与自我参照的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的类,看起来像这样...
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>();
}
}
...其中ID是主键和的ParentId是外键。当我运行这段代码,我得到无效的对象名称ItemToItem。例外,我想不出有什么不对?我好像NHibernate的尝试从表中选择名为ItemToItem或类似的东西?
... 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?
推荐答案
正确的方式自我引用
// 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();
这篇关于功能NHibernate automappings与自我参照的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!