【问题标题】:NHibernate mapping an IDictionary problemsNHibernate 映射一个字典问题
【发布时间】:2012-12-12 05:07:05
【问题描述】:

我有一个 NHibernate 映射问题,我可以使用帮助解决 - 文档和示例对我来说似乎很不清楚。

我有一个类,其中包含另一个类的字典。我不确定正确的映射,我尝试过的所有操作要么映射失败,要么在读取数据时出现 NHibernate 异常。

这两个类是:

public class SnippetConfigParam
{
    public virtual int          SnippetValueKey { get; set; }
    public virtual string       ParamName { get; set; }
    public virtual string       Value{ get; set; }
}

public  class SnippetConfig
{
    public virtual int          SnippetKey { get; set; }


    public virtual ESnippetType Type{ get; set; }
    public virtual string       Name { get; set; }

    public virtual IDictionary<string, SnippetConfigParam> Params { get; set; }


    public virtual string       Description{ get; set; }


    public virtual VendorPage   Page{ get; set; }
}

我最后一次映射尝试是

<map name="Params"  table="SnippetConfigValue" lazy="false">
    <key column="SnippetConfigKey" />
    <index column="SnippetValueKey"  type="Int32"/>    
    <composite-element class ="SnippetConfigParam">
        <property name="ParamName"  />
        <property name="Value" />
    </composite-element>      
</map>

结果:

System.InvalidCastException:无法将“System.Int32”类型的对象转换为“System.String”类型。

所以我显然不明白一些事情。数据库表是:

Create Table SnippetConfig
    SnippetKey  int not null, 
    ...
    PrimaryKey( 'SnippetKey' )

  Create Table SnippetConfigValue
    SnippetValueKey  int  not null,
    ...
    PrimaryKey( 'SnippetValueKey' ),
    Key  'fk' ( 'SnippetConfigKey' ),
    Constraint 'fk' foreign key ('SnippetConfigKey' ) references 'SnippetConfig' ('SnippetKey' )...

任何建议将不胜感激。

【问题讨论】:

    标签: c# asp.net-mvc nhibernate


    【解决方案1】:

    在 NHibernate 中映射字典可能有点棘手。请参阅此处的详细说明:Ayende's post about &lt;map&gt;。 理解它的关键在于TKeyTValue(IDictionary&lt;TKey, TValue&gt;)的映射关系

    • TKey 由&lt;index&gt; 元素表示
    • TValue 可以是元素、复合元素、一对多

    因为你的TKey字符串

    public virtual IDictionary<string, SnippetConfigParam> Params { get; set; }
    

    表示它的映射不能是 int

    <index column="SnippetValueKey"  type="Int32"/>
    

    Params 属性更改为IDictionary&lt;int, SnippetConfigParam&gt;,它应该可以工作。

    注意:如果要填充类 SnippetConfigParam 的属性 SnippetValueKey,请扩展组件

    <composite-element class ="SnippetConfigParam">
        <property name="SnippetValueKey" formula="SnippetValueKey " 
                  insert="false" update="false" />
        <property name="ParamName"  />
        <property name="Value" />
    </composite-element>
    

    【讨论】:

    • 完美地阐明了 Radim。我确实希望 IDictionary 是一个字符串,因为我想按名称访问参数。所以我将索引更改为 。类型似乎是强制性的,没有体现出来。我注意到填充 SnippetValueKey 是什么意思 - 我需要将键作为本机主键,但实际上并不关心它。我将检查公式并插入和更新 pars 以了解效果。再次感谢。
    • 我要注意的是,您的 C# 类 SnippetConfigParam 具有属性 SnippetValueKey。这不会被 NHibernate 填充,除非您使用 formulainsert/update false 添加映射...否则它将一直是0。只是一个注释;)
    猜你喜欢
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多