2011-10-27 42 views
7

我正在嘗試使用CompositeId映射到遺留系統。源數據庫有一個複合主鍵,所以我不能使用正常的this.Id映射。CompositeId原因無法編譯映射文檔錯誤

這是我嘗試它映射:

public PriorityListPartMap() 
{ 
    this.Schema("EngSchedule"); 

    this.Table("vPriorityListPart"); 

    this.CompositeId().KeyProperty(x => x.AssemblyPartNumber).KeyProperty(x => x.PartNumber); 

    this.Map(x => x.CurrentDueDate); 

    this.Map(x => x.OrderLine); 

    this.Map(x => x.OrderNumber); 

    this.Map(x => x.PartDescription); 

    this.Map(x => x.ProductCode); 

    this.Map(x => x.Revision); 
} 

當我嘗試創建會話工廠這個映射導致錯誤: 無法編譯映射文件:(XmlDocument的)

我試着

this.Id(x => x.AssemblyPartNumber).GeneratedBy.Assigned(); 

錯誤消失與映射,但我真的不能使用該罪:去除CompositeId映射,並取代了它AssemblyPartNumber不是唯一的。

是否有不同的方式映射到具有複合主鍵的表?

感謝,

馬修·麥克法蘭

回答

25

什麼是內部異常 「無法編譯映射文件:(XmlDocument的)」?我的理論是這樣的:「composite-id類必須覆蓋Equals():YOURNAMESPACE.PriorityListPart」。

對於需要複合標識的實體,對象本身被用作關鍵字。爲了使'相同'的對象被識別爲這樣,你需要重寫Equals和GetHashCode方法。

一個實例的Equals對你的實體的方法是這樣的:

public override bool Equals(object obj) 
{ 
    var other = obj as PriorityListPart; 

    if (ReferenceEquals(null, other)) return false; 
    if (ReferenceEquals(this, other)) return true; 

    return this.AssemblyPartNumber == other.AssemblyPartNumber && 
     this.PartNumber == other.PartNumber; 
} 

對你的實體的一個例子GetHashCode的方法是這樣的:

public override int GetHashCode() 
{ 
    unchecked 
    { 
     int hash = GetType().GetHashCode(); 
     hash = (hash * 31)^AssemblyPartNumber.GetHashCode(); 
     hash = (hash * 31)^PartNumber.GetHashCode(); 

     return hash; 
    } 
} 

這也意味着,如果你想要檢索一個對象,你不能有一個鍵來完成它。要使用組合鍵組件正確檢索特定對象,您使用的鍵實際上就是對象的一個​​實例,組合鍵組件設置爲您希望檢索的實體。

這就是爲什麼必須重寫Equals()方法的原因,以便NHibernate能夠根據您在Equals方法中指定的內容來確定您實際嘗試檢索哪個對象。

+0

這是**輝煌的**!完美工作。我原來的錯誤沒有內部異常,它是空的,但你的解決方案無論如何都是正確的。非常感謝您的幫助。 –

+0

完美的解決方案 - 適合我!我的實體由http://nmg.codeplex.com/創建,沒有Equals。 – Henrik

相關問題