流畅的NHibernate映射字典包装类

时间:2013-01-24 16:17:57

标签: nhibernate fluent-nhibernate fluent-nhibernate-mapping

我正在尝试将现有的HMB映射文件迁移到Fluent映射,但是已经取消了映射以下类别(简化)。

public interface IThing
{
    int Id { get; }
    string Name { get; }
    ISettings Settings { get; }
}

public class Thing : IThing { /* Interface implementation omitted */ }

public interface ISettings
{
    string SomeNamedSetting1 { get; }
    bool SomeNamedSetting2 { get; }
    int SomeNamedSetting3 { get; }
}

public class Settings : ISettings
{
    Dictionary<string, string> rawValues;

    public string SomeNamedSetting1 { get { return rawValues["SomeNamedSetting1"]; } }
    public bool SomeNamedSetting2 { get { return Convert.ToBoolean(rawValues["SomeNamedSetting2"]); } }
    public int SomeNamedSetting3 { get { return Convert.ToInt32(rawValues["SomeNamedSetting3"]); } }
}

我们对接口IThing进行编码,并通过ISettings接口上定义的帮助器属性访问其设置。这些设置存储在一个名为“设置”的表中的数据库中,该表是一组带有外键的键值对。

现有的映射文件如下:

                     

<component name="Settings" lazy="false" class="Settings, Test">
  <map name="rawValues" lazy="false" access="field" table="Setting">
    <key column="Id" />
    <index column="SettingKey" type="String" />
    <element column="SettingValue" type="String" />
  </map>
</component>

我所挣扎的是组件定义,因为我找不到class属性的Fluent等价物。这就是我到目前为止所拥有的:

public class ThingMap : ClassMap<Thing>
{
    public ThingMap()
    {
        Proxy<IThing>();
        Id(t => t.Id);
        Map(t => t.Name);

        // I think this is the equivalent of the private field access
        var rawValues = Reveal.Member<Settings, IDictionary<string, string>>("rawValues");

        // This isn't valid as it can't convert ISettings to Settings
        Component<Settings>(t => t.Settings);

        // This isn't valid because rawValues uses Settings, not ISettings
        Component(t => t.Settings, m =>
        {
            m.HasMany(rawValues).
            AsMap("SettingKey").
            KeyColumn("InstanceId").
            Element("SettingValue").
            Table("Setting");
        });

        // This is no good because it complains "Custom type does not implement UserCollectionType: Isotrak.Silver.IInstanceSettings"
        HasMany<InstanceSettings>(i => i.InstanceSettings).
            AsMap("SettingKey").
            KeyColumn("InstanceId").
            Element("SettingValue").
            Table("Setting");
    }
}

1 个答案:

答案 0 :(得分:1)

对于同一条船上的任何人,我最终破解了它。

Component<Settings>(i => i.Settings, m =>
{
    m.HasMany(rawValues).
    AsMap<string>("SettingKey").
    KeyColumn("InstanceId").
    Element("SettingValue").
    Table("Setting");
});

现在看来很明显!