编程语言
首页 > 编程语言> > c#-使用FluentNHibernate的引用上的CustomType

c#-使用FluentNHibernate的引用上的CustomType

作者:互联网

我正在使用一个名为LanguageExt的库.该库提供了一些工具来处理C#代码中的函数式编程.我还使用FluentNHibernate来将域类映射到数据库.

当属性为可空值时,我想使用Option< T>来自LanguageExt.它是一个保留值或等于None的结构.

我的类模型之一,例如Car具有一个可选属性,例如类型为Option< Window>的天窗.像这样:

public class Car
{
   Window _sunroof;
   Option<Window> Sunroof
   {
     get => Optional(_sunroof);
     set => _sunroof = value.IfNoneUnsafe(() => null);
   }
}

我的映射是这样的:

References<Window>(x => x.Sunroof, "idSunroof")
   .Not.Nullable();

我的问题是:在知道它们不共享相同的返回类型的情况下,如何使用其后备字段映射天窗属性?

解决方法:

It’s a domain model but also mapped to some table in the database via the mapping configuration done by FluentNHibernate.

我认为这不是一个好主意.您正在尝试在这一节课中做三(或四)件事,我会分开做.

我建议为NHibernate(可能称为CarDto)和业务模型(可能称为Car)使用DTO.这样,CarDto可以由于与数据库相关的原因(而不是由于建模的原因)而发生变化,而Car可以由于建模的原因(但并非因数据库原因)而发生变化.例如,函数式编程将使业务模型不可变,但是NHibernate可能要求其DTO是可变的.如果您同时使用相同的类型,那么您将无法满足所有设计约束.

how do I map the Sunroof property using its backing field knowing that they don’t share the same return type?

我认为您不应该拥有具有不同类型的属性和支持字段.对于CarDto,使用null表示不存在Window.然后,当从CarDto映射到Car时,将null映射为None状态(通过当前使用的Optional函数).然后,当从Car映射到CarDto时,将None映射回null(通过当前使用的IfNoneUnsafe方法).

您的汽车课

>是NHibernate的DTO,
>是您的商业模式,
>包含从DTO到业务模型的映射,以及
>包含从业务模型到DTO的映射.

这是我上面提到的三到四件事(取决于您将映射算作一件事还是两件事).

添加2019-02-20

[your answer is] not a solution to my problem but a proposal for a better architecture

两者都是.

I fully agree with what you said and I would be very happy to do that but I can’t. In my code base I have more than 250 model classes which are quite badly designed and with a lot of wrongly made dependencies. I can’t afford to refactor all of that at once.

我不建议您立即更改所有内容.离得很远.在马丁·福勒(Martin Fowler)的Refactoring风格中,我建议随着时间的推移进行许多小的更改.

例如,将Car更改为

public class Car
{
   Option<Window> Sunroof
   {
     get => Optional(SunroofBacking);
     set => SunroofBacking = value.IfNoneUnsafe((Window) null);
   }
   Window SunroofBacking { get; set; }
}

并出于业务逻辑原因使用Sunroof属性(“更好”的名称),以及出于NHibernate原因使用SunroofBacking属性?

标签:nhibernate,c,fluent-nhibernate,language-ext
来源: https://codeday.me/bug/20191108/2006519.html