如何使用FluentNHibernate配置通用组件?

时间:2010-05-21 19:34:18

标签: nhibernate fluent-nhibernate nhibernate-mapping components

以下是我要配置映射的组件

public class Range<T> : ValueObject
{
    public virtual T Start {get; set;}
    public virtual T Finish {get; set;}
}

在我的域中,我有许多实体具有Range&lt;属性。 DateTime&gt;,范围&lt; int&gt; ...对于具有属性x的特定类,我们以这种方式配置组件:

 persistenceModel.FindMapping<Customer>()  
     .Component<Address>            (  
                 x => x.CustomerAddress,  
                 m =>  
                 {  
                     m.Map(x => x.Street).WithLengthOf(100);  
                     m.Map(x => x.PostalCode).WithLengthOf(6);  
                     m.Map(x => x.Town).WithLengthOf(30);  
                     m.Map(x => x.Country).WithLengthOf(50);  
                 }); 

如何将整个域的约定视为通用T? 我想念一些东西吗? FluentNhibernate是不可能的?

1 个答案:

答案 0 :(得分:1)

您不应该为此目的使用FindMapping。能够通过该方法改变映射是一种疏忽,绝对不应该依赖。该方法用于检查持久性模型,而不是改变它。如果您正在使用自动化,则应该查看overrides


我相信您的问题可以通过ICompositeUserType实施来解决;在线提供了一些关于如何实现这些资源的资源,特别是generic composite user type implementation。您只需正常映射范围属性,但使用CustomType为其提供用户类型。

Map(x => x.Range)
  .CustomType<RangeUserType>();

您也可以使用新引入的ComponentMap功能,但不支持在不使用基类的情况下映射 open 泛型类型。

这样的事可能有用:

public abstract class RangeMap<T> : ComponentMap<T>
{
  protected RangeMap()
  {
    Map(x => x.Start);
    Map(x => x.Finish):
  }
}

public class IntRangeMap : RangeMap<int>
{}

public class DateRangeMap : RangeMap<DateTime>
{}

不可否认,这并不理想。

相关问题