c# - 无法解析 KeyColumn 上的属性

标签 c# nhibernate fluent-nhibernate

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

解决方案

  1. 扩展模型

我们可以将其添加到模型中

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);
  1. 只需更改参数

事实上,这将是最简单的解决方案...将调用方更改为以现有映射为目标:

var list = ByParameter<MenuItem>("Parent.MenuItemId", 123);

因为 Parent的属性 MenuItemId(<id>Id())显示(它是列 ParentId) - 我们不需要 JOIN . NHibernate 将生成预期的简单查询

关于c# - 无法解析 KeyColumn 上的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30019658/

相关文章:

c# - 流利的 NHibernate 错误 : The entity 'ClassMap` 1' doesn' t have an Id mapped

sql-server - 如何在 HQL 中使用 Datediff()

.net - NHibernate - 如何映射到没有表的类(用于自定义 sql 查询)

c# - nhibernate "cascade="all-delete-orphan”错误

c# 和 LINQ- 根据对象的 ID 对对象进行分组,然后在其中找到共同的值

c# - 无法将类型 'System.Data.EnumerableRowCollection<System.Data.DataRow>' 转换为 generic.list<T>

database - NHibernate 桌面应用程序 : should it use multiple sessions?

nhibernate - 从 Fluent Nhibernate 生成 XML 映射

c# - 在 C# 中确定 WiFi 的当前链接速度

c# - 在 C# 中将 CIL 代码更改为 native 代码