2012-02-23 110 views
1

比方說,我有一個產品類,它有一個類屬性。爲什麼爲外鍵創建兩列?

public class Product : Entity<int> // Base class defines the Id 
{ 
    public virtual ProductCategory Category { get; set; } 
} 

映射文件是簡單

public class ProductMap : ClassMap<Product> 
{ 
    public ProductMap() 
    { 
    Id(x => x.Id); 
    References(x => x.Category).Nullable(); 
    } 
} 

使用SchemaExport.Create這造成兩列在我的數據庫,ProductCategoryIdCategoryId。根據我的慣例,只有CategoryId應該存在。兩者都可以爲空,但僅使用CategoryId。無論如何,ProductCategoryId始終爲空,並且它是具有外鍵約束的列。

這是爲什麼?我實際上找不到代碼的任何問題,只要我可以使用CategoryId列告訴一切正常。我可以查詢/保存/更新有或沒有類別。如果我沒有去查看數據庫,我甚至不知道其他列是否存在,但是當我不知道它是什麼時,我不喜歡有一個列。是否有它存在的原因,或者我映射可空引用的方式有什麼問題?

回答

0

那麼這個問題與ProductProductMap類沒什麼關係。問題出在ProductCategory地圖上。

這就是在數據庫中創建ProductCategoryId列的原因。

public class ProductCategoryMap : ClassMap<ProductCategory> 
{ 
    public ProductCategoryMap() 
    { 
     Id(x => x.Id); 
     // Other mappings 
     HasMany(x => x.Products).Inverse().Cascade.AllDeleteOrphan(); 
    } 
} 

該映射無法說明它應該使用現有的CategoryId列。在映射文件上指定它,甚至將Product類中的Category屬性重命名爲ProductCategory,強制它停止創建不同的列。

相關問題