【问题标题】:Fluent NHibernate mapping tables with similar properties but no inheritance hierarchy具有相似属性但没有继承层次结构的流畅 NHibernate 映射表
【发布时间】:2015-09-23 16:30:38
【问题描述】:

我在为以下模型结构开发一组健全的 Fluent NHibernate 映射时遇到问题:

public class BaseLookup
{
    public virtual int Id {get; set;}
    public virtual string Code {get; set;}
    public virtual string Value {get; set;}
    public virtual bool Active {get; set;}
}
public class Subdivision : BaseLookup { }
public class AvisCode : BaseLookup { }
public class District : BaseLookup { }
/*etc.*/

这些查找都共享属性,但彼此之间没有任何关系。这些表对报告具有特殊的语义含义,并且将在存储过程中专门引用,因此我不希望将它们混入需要我使用鉴别器的通用“查找”表中。这似乎消除了我的映射中的 Table-per-Hierarchy 和 Table-per-Sublass 策略。我也很难使用 Table-per-Concrete-Class 因为每个查找都有自己的标识列 - 我不想在应用程序中手动分配一个 Id,并且没有要求 Id 在所有这些中都是唯一的表格。

目前,我的映射如下所示,并且对于 BaseLookup 的每个超类都是相同的:

public class AvisCodeMap : ClassMap<AvisCode>
{
    public AvisCodeMap()
    {
        Schema(Schemas.pva.ToString());
        Id(x => x.Id).GeneratedBy.Identity();
        Map(x => x.Code).Not.Nullable();
        Map(x => x.Value).Not.Nullable();
    }
}

是否没有映射约定允许我将重复映射提取到可重用代码块?

【问题讨论】:

    标签: c# fluent-nhibernate


    【解决方案1】:

    如果我正确理解您的问题,您可能需要创建一个通用基类映射,然后在派生映射中重用它。

    示例如下:

    public class BaseLookupMap<T> : ClassMap<T> where T : BaseLookup
    {
         public BaseLookupMap()
         {
            // ... base mapping code goes here ...
         }
    }
    

    创建基本类型:

    public class BaseLookupMap : BaseLookupMap<BaseLookup>
    {  
    }
    

    以及派生类映射:

    public class AvisCodeMap : BaseLookupMap<AvisCode>
    {
        public AvisCodeMap()
        {
            Polymorphism.Explicit();
    
            // ... your other mappings here, if needed ...
        }
    }
    

    HTH。

    【讨论】:

    • 有效!我全神贯注于寻找一种 NHibernate 的方法,以至于我忘记了尝试使用该语言的工具。我注意到即使没有 Polymorphism.Explicit(),该技术也可以工作。这只是为了充当警卫,以免消费者尝试查询无意义的基类吗?
    • @FolksymAndrew 对迟到的评论感到抱歉。查看 Hibernate 的 polymorphism 文档,它指出定义 explicit 多态性 means that class instances will be returned only by queries that explicitly name that class. Queries that name the class will return only instances of subclasses mapped ... Explicit polymorphisms is useful when two different classes are mapped to the same table。希望这能解决问题。
    猜你喜欢
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多