【问题标题】:How can I use custom objects with NHibernate如何在 NHibernate 中使用自定义对象
【发布时间】:2017-10-16 08:27:47
【问题描述】:

请看下面的域对象:

public Class Person
{
    public virtual Guid Id { get; protected set; }
    public virtual string FirstName { get; protected set; }
    public virtual string Surname { get; protected set; }
    public virtual System.DateTime DateOfBirth { get; protected set; }

        //Domain methods are here.

}

以及下面的 NHibernate 映射:

public class PersonMap : ClassMapping<Person>
{
    public PersonMap()
    {
        Id<Guid>(x => x.Id);
        Property<string>(x => x.FirstName);
        Property<string>(x => x.Surname);
        Property<DateTime>(x => x.DateOfBirth);
    }

}

这按预期工作。假设我想将域模型更改为:

public Class Person
{
    public virtual Guid Id { get; protected set; }
    public virtual FirstName FirstName { get; protected set; }
    public virtual Surname Surname { get; protected set; }
    public virtual DateOfBirth DateOfBirth { get; protected set; }
}

请注意,原始类型已替换为对象。我这样做的原因是为了消除这里描述的原始痴迷:http://enterprisecraftsmanship.com/2015/03/07/functional-c-primitive-obsession/

我已阅读此处的文档(第 144 页):http://stc.sbu.ac.ir/AdminTools/Docs/Files/nhibernate_reference.pdf。它告诉我引入自定义类型。我也读过这个问题:nHibernate mapping to custom types。我仍在努力使用 NHibernate 代码映射来做到这一点,因此也是这个问题的原因。

【问题讨论】:

  • 您是否考虑过通过组件映射它们 (github.com/jagregory/fluent-nhibernate/wiki/…)?如果您的数据在同一个表中,这可能是一个更容易的起点。
  • @David Osbourne,+1 - 该链接实际上非常有帮助。我将 Fluent NHibernate 中的代码改编为代码映射,现在它可以按预期工作(请参阅我的答案)。你能发布一个答案,以便我可以给予一些信任吗?

标签: c# nhibernate domain-driven-design


【解决方案1】:

您是否查看过通过components 映射它们?

如果您的数据在同一个表中,那么与自定义类型相比,这可能是一个更容易的起点。

【讨论】:

  • 对于组件的引用。 +1。
  • 在我标记你的答案之前。您知道是否可以将 NHibernate 字段映射到类构造函数而不是类属性(我在下面的答案中使用了类属性)?
  • 不确定。如果您查看此处 (nhibernate.info/doc/nh/en/…),您可以看到可用的访问策略。好像不支持构造函数。
【解决方案2】:

继 David Osbournes 的评论之后;答案是这样做:

Component(x => x.FirstName, y =>
                {
                    y.Property<string>(z => z.FirstName);
                });

NHibernate 使用类的 FirstName 属性映射到数据库。

【讨论】:

    猜你喜欢
    • 2014-09-14
    • 2010-09-18
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    相关资源
    最近更新 更多