2009-12-10 102 views
0

問題:有沒有一種方法可以根據上下文將單個外鍵映射到多個互斥表格?使用Fluent NHibernate將單個字段映射到多個表格

背景...

以我具體實例中,我有以下域圖,表示一個保險索賠可以是相對車輛屬性:

public enum InvolvedPartyContext 
{ 
    Vehicle = 1, 
    Property = 2 
} 

public class Claim 
{ 
    public virtual Guid Id { get; set; } 
    public virtual InvolvedPartyContext InvolvedPartyContext { get; set; } 
    public virtual Vehicle Vehicle { get; set; } // set if Context = Vehicle 
    public virtual Property Property { get; set; } // set if Context = Property 
} 

public class Vehicle { //... } 

public class Property { //... } 

SQL看起來像這樣(注意單個外鍵InvolvedPartyId):

CREATE TABLE Claims ( 
Id uniqueidentifier NOT NULL, 
InvolvedPartyContext int NOT NULL, 
InvolvedPartyId uniqueidentifier NOT NULL 
) 

CREATE TABLE Vehicles (
    Id uniqueidentifier NOT NULL, 
    Registration varchar(20) NOT NULL 
) 

CREATE TABLE Properties (
    Id uniqueidentifier NOT NULL, 
    PostCode varchar(20) NOT NULL 
) 

爲如權利要求所述的功能NHibernate映射文件:

public ClaimMap() 
    { 
     Id(x => x.Id); 
     Map(x => x.InvolvedPartyContext).CustomTypeIs(typeof(InvolvedPartyContext)); 
     References(x => x.Vehicle, "InvolvedPartyId"); 
     References(x => x.Property, "InvolvedPartyId"); 
    } 

這拋出異常的 「用於此SqlParameterCollection以計數{M}無效的索引{N}」,因爲同樣的字段(InvolvedPartyId)是映射兩次。一個簡單的解決方法是創建VehicleId和PropertyId字段,但在現實世界中有更多的上下文,所以這不是很靈活。

回答

2

就我個人而言,我不會用你有的設計去。相反,我會分別創建Claim類的子類,VehicleClaimPropertyClaim

public class VehicleClaim : Claim 
{ 
    public virtual Vehicle Vehicle { get; set; } 
} 

然後改變你的映射使用您的InvolvedPartyContext列作爲鑑別(其中NHibernate的使用,以確定該行表示其類列),並創建子類映射每個子類。

public class ClaimMap : ClassMap<Claim> 
{ 
    public ClaimMap() 
    { 
    Id(x => x.Id); 
    DiscriminateSubClassesOnColumn("InvolvedPartyContext"); 
    } 
} 

public class VehicleClaimMap : SubclassMap<VehicleClaim> 
{ 
    public VehicleClaimMap() 
    { 
    DiscriminatorValue(1); 
    References(x => x.Vehicle); 
    } 
} 

如果你確實想與你有什麼運行,你應該看看任何映射;關於它們的文檔並不多,但您使用的是ReferencesAny方法。

+0

你的使用鑑別器的建議是一個很好的建議,但不幸的是我們的設計是固定的。找到一些很好的參考文獻Ayende的博客上有任何文檔,所以我會沿着這條路線走下去。謝謝! – Dunc 2010-01-18 17:50:22

相關問題