【问题标题】:NHibernate bycode mapping to a protected collectionNHibernate bycode 映射到受保护的集合
【发布时间】:2014-06-26 22:33:19
【问题描述】:

我正在尝试(通过代码)将受保护的集合映射到一个包,但我很挣扎。例如

public class MyClass
{
    ....
    protected virtual ICollection<Items> MyItems { get; set; }
    ....
}

public class MyClassMapping : ClassMapping<MyClass>
{
    ...
    Bag(x => x.MyItems, map =>
    {
        ....
    }
    ...
}

它抛出一个映射异常,内部异常为“ArgumentNullException:值不能为空。参数名称:localMember”。如果“MyItems”集合是公开的,它就可以正常工作。

我关注了这篇文章 (https://groups.google.com/forum/#!topic/nhusers/wiH1DPGOhgU),它建议使用采用字符串的方法重载。例如

public class MyClassMapping : ClassMapping<MyClass>
{
    ...
    Bag("MyItems", map =>
    {
        ....
    }
    ...
}

但这会产生编译错误“方法的类型参数....无法从用法中推断出来。尝试显式指定类型参数”。

是否可以映射到受保护的集合(我使用的是 NH 3.3)?谁能举个例子?

谢谢, 切特

【问题讨论】:

    标签: nhibernate mapping nhibernate-mapping protected mapping-by-code


    【解决方案1】:

    我们可以在这里看到重载的方法:PropertyContainerCustomizer.cs

    public void Bag<TElement>(string notVisiblePropertyOrFieldName
      , Action<IBagPropertiesMapper<TEntity, TElement>> collectionMapping
      , Action<ICollectionElementRelation<TElement>> mapping)
    { ... }
    

    我们必须作为通用模板传递的是TElement,即ICollection&lt;TElement&gt;。

    因为定义是:

    // TElement is Items
    protected virtual ICollection<Items> MyItems { get; set; }
    

    解决方案:我们要做的就是像这样声明映射

    // the TElement must be expressed explicitly as Items
    Bag<Items>("MyItems", map =>
    {
        ....
    }
    

    【讨论】:

    • 嗨,Radmin,我刚刚验证了这个,它可以正常工作,非常感谢。
    • 很高兴看到这一点。享受 NHibernate ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多