我在 ByParameter
返回时收到此错误,因为 KeyColumn
我猜,我该如何使它工作?
could not resolve property: ParentId of: Entity.MenuItem
Entity.MenuItem.READ.ByParameter("ParentId", 3);
代码:
public static IList<T> ByParameter(String Parameter, Object Value)
{
using (var session = NHibernateHelper<T>.OpenSession())
{
var conjunction = new Conjunction();
conjunction.Add(Restrictions.Eq(Parameter, Value));
return session.CreateCriteria(typeof(T)).Add(conjunction).List<T>();
}
}
class MenuItemMap : Mapper<MenuItem>
{
public MenuItemMap()
{
Id(x => x.MenuItemId);
Map(x => x.Text);
HasMany(x => x.Children).KeyColumn("ParentId").Fetch.Select();
References(x => x.Parent).Fetch.Select();
}
}
最佳答案
基于Exception
我会说,我们可以面对这个问题,以防万一 - 调用方看起来像这样:
var list = ByParameter<MenuItem>("ParentId", 123);
而且因为上面的代码片段没有显示类 MenuItem
包含 ValueType
(非引用) 属性 ParentId:
public class MenuItem
{
// the <id>
public virtual int MenuItemId { get; set; }
// References (many-to-one)
public virtual MenuItem Parent { get; set; }
// this seems to be not presented on MenuItem
// public virtual int ParentId { get; set; }
// HasMany (one-to-many)
public virtual IList<MenuItem> Children { get; set; }
解决方案
- 扩展模型
我们可以将其添加到模型中
public virtual int ParentId { get; set; }
并扩展映射
// many-to-one is using the same column - so this will be WRITABLE
References(x => x.Parent).Fetch.Select();
// just a ValueType property - READONLY
Map(x => x.ParentId)
.Readonly() // or .Update(false).Insert(false)
;
现在就可以了
var list = ByParameter<MenuItem>("ParentId", 123);
- 只需更改参数
事实上,这将是最简单的解决方案...将调用方更改为以现有映射为目标:
var list = ByParameter<MenuItem>("Parent.MenuItemId", 123);
因为 Parent
的属性 MenuItemId(<id>
或 Id()
)显示(它是列 ParentId) - 我们不需要 JOIN . NHibernate 将生成预期的简单查询
关于c# - 无法解析 KeyColumn 上的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30019658/