2010-11-15 94 views
1

我遇到了一定的映射問題。比方說,我有三個評估,所有獲得過一個基地Assessment如何使用NHibernate將派生屬性映射到基類上?

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爲了得到一個評估的總傷害成本。

在我流利的NHibernate映射,我映射到各DamageCostTotal對於每個具體的評估:

Session.Query<IndividualAssessment>().OrderBy(x => x.DamageCostTotal); 
Session.Query<BusinessAssessment>().OrderBy(x => x.DamageCostTotal); 
Session.Query<InfrastructureAssessment>().OrderBy(x => x.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<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 

正如你所看到的,它是正確創建的公式,但是當它被InfrastructureAssessment性質,而不是公式做了ORDER BY,它只有單吧。有誰知道如何映射基地DamageCostTotal,以便這個查詢將返回正確的結果?

回答

1

一種解決方案是映射基類中的DamageCostTotal。如果沒有一個,爲表中的DamageCostTotal創建一個列。在這種情況下,NHibernate不需要知道公式,這很好,因爲這些類已經在進行繁重的工作。

您的查詢應導致SQL與此類似...

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

謝謝,我試了一下,它的偉大工程。 – 2010-11-16 04:27:25

相關問題