【问题标题】:How do I map a dictionary using Fluent NHibernate automapping?如何使用 Fluent NHibernate 自动映射来映射字典?
【发布时间】:2009-12-21 22:33:28
【问题描述】:

我有一个这样的实体:

public class Land
{
    public virtual IDictionary<string, int> Damages { get; set; }
    // and other properties
}

每次我尝试通过以下代码使用自动映射时:

var sessionFactory = Fluently.Configure()
    .Database(SQLiteConfiguration.Standard.InMemory)
    .Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<Land>))
    .BuildSessionFactory();

我收到以下错误:

{"The type or method has 2 generic parameter(s), but 1 generic argument(s) were
provided. A generic argument must be provided for each generic parameter."}

谁能告诉我我做错了什么?此外,这只是一个简单的例子。我的字典远不止这本。

【问题讨论】:

标签: configuration fluent-nhibernate dictionary automapping


【解决方案1】:

使用 NHibernate 是不可能的。

【讨论】:

  • 您的意思是这对于 Fluent NHibernate 自动映射、作为一个整体的 Fluent NHibernate(也意味着对于 fluent 映射)或 NHibernate 本身是不可能的?
  • NHibernate 本身。目前我不知道任何可以自动映射字典的 ORM。
  • 你是对的,你必须手动映射它。使用 Fluent,它会是 References(x =&gt; x.Dictionary).AsMap&lt;int&gt;("keyColumn").Element("valueColumn", c =&gt; c.Type&lt;string&gt;());
【解决方案2】:

发现了一些关于此isn't possible 的痕迹。一些痕迹,即it's recently implemented

仍在调查中。 :)


This looks quite promising(尚未测试)。

所以,在你的情况下,它应该看起来像=>

public class LandMap : ClassMap<Land>
{
    public LandMap()
    {
        (...)

        HasMany(x => x.Damages)
            .WithTableName("Damages")
            .KeyColumnNames.Add("LandId")
            .Cascade.All()
            .AsMap<string>(
                index => index.WithColumn("DamageType").WithType<string>(),
                element => element.WithColumn("Amount").WithType<int>()
            );
    }
}

请记住 - 它应该。我没有测试它。

【讨论】:

  • 那是流畅的映射。我正在寻找适用于自动映射的东西,因为我的所有实体都有大约 50 个字典。
  • 啊……抱歉。不知何故没有注意到automapping。我会看看。 :)
【解决方案3】:

理论上应该适用于自动映射的一种可能的解决方法:

public class DamagesDictionary : Dictionary<string, int>
{
}

土地.cs

public class Land
{
   public virtual DamagesDictionary Damages { get; set; }
   // and other properties
}

或更通用的方法...

public class StringKeyedDictionary<T> : Dictionary<string, T>
{
}

土地.cs

public class Land
{
   public virtual StringKeyedDictionary<int> Damages { get; set; }
   // and other properties
}

【讨论】:

  • 我认为这是一个被低估的答案 - 有时更简单地制作另一个带有 2 个属性(键、值)的 POCO,并参考如果你懒得写映射(懒惰,是的..推荐人,不...但是...)
猜你喜欢
  • 2012-04-16
  • 1970-01-01
  • 2011-04-10
  • 1970-01-01
  • 1970-01-01
  • 2011-02-10
  • 2011-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多