如何使用NHibernate在基类上映射派生属性?

时间:2010-11-15 20:34:43

标签: c# sql nhibernate fluent-nhibernate nhibernate-mapping

我遇到某种映射问题。假设我有三个评估都是基于Assessment

public abstract class Assessment
{
    public abstract int DamageCostTotal { get; set; }
}

public class IndividualAssessment
{
    public virtual int DamageCostHouse { get; set; }
    public virtual int DamageCostCar { get; set; }
    public virtual int DamageCostBelongings { get; set; }
    public override DamageCostTotal
    {
        get { return DamageCostHouse + DamageCostCar + DamageCostBelongings; }
    }
}

public class BusinessAssessment
{
    public virtual int DamageCostBuilding { get; set; }
    public virtual int DamageCostGoods { get; set; }
    public virtual int DamageCostOther { get; set; }
    public override DamageCostTotal
    {
        get { return DamageCostBuilding + DamageCostGoods + DamageCostOther; }
    }
}

public class InfrastructureAssessment
{
    public virtual int DamageCostStructure { get; set; }
    public virtual int DamageCostEstimatedRepair { get; set; }
    public override DamageCostTotal
    {
        get { return DamageCostStructure + DamageCostEstimatedRepair; }
    }
}

换句话说,三种评估类型IndividualAssessmentBusinessAssessmentInfrastructureAssessment都有特定的损失成本,但它们都实现了基类“DamageTotalCost为了得到一个评估的总损伤成本。

在我的Fluent NHibernate映射中,我为每个特定评估映射了每个DamageCostTotal:

// individual assessment
Map(x => x.DamageCostTotal)
    .Access.Readonly()
    .Formula("DamageCostHouse + DamageCostCar + DamageCostBelongings");
// the other two are mapped the same way, just with a different formula

当我查询特定的评估类型时,这非常有用:

Session.Query<IndividualAssessment>().OrderBy(x => x.DamageCostTotal);
Session.Query<BusinessAssessment>().OrderBy(x => x.DamageCostTotal);
Session.Query<InfrastructureAssessment>().OrderBy(x => x.DamageCostTotal);

但是当我尝试查询基本评估类型时:

Session.Query<Assessment>().OrderBy(x => x.DamageCostTotal);

它会生成错误的SQL(为了便于阅读而清理一下):

SELECT ...
    DamageCostHouse + DamageCostCar + DamageCostBelongings as formula0_0_,
    DamageCostBuilding + DamageCostGoods + DamageCostOther as formula1_0_,
    DamageCostStructure + DamageCostEstimatedRepair as formula2_0_,
    FROM [Assessment] this_
    ORDER BY DamageCostStructure + DamageCostEstimatedRepair

正如您所看到的,它正确地创建了公式,但是当它执行ORDER BY时,它只按InfrastructureAssessment属性而不是公式排序。有谁知道如何映射基础DamageCostTotal,以便此查询将返回正确的结果?

1 个答案:

答案 0 :(得分:1)

一种解决方案是在基类中映射DamageCostTotal。如果没有,则在表中为DamageCostTotal创建一列。 NHibernate不需要知道这个场景中的公式,这很好,因为类已经完成了繁重的工作。

您的查询应该导致类似于此的SQL ...

SELECT ..., this_.DamageCostTotal FROM Assessment this_ ORDER BY this_.DamageCostTotal