0

是否有可能使用一個自動遞增的身份索引和一個將其鏈接到另一個表的外鍵映射實體?在實體框架4,一個身份和一個外部使用兩個鍵?

public class Item 
{ 
    public int ItemID { get; set; } 

    [StringLength(20)] 
    public string Barcode { get; set; } 

    [StringLength(50)] 
    public string Name { get; set; } 

    [StringLength(50)] 
    public string Description { get; set; } 

    public decimal Price { get; set; } 

    [ForeignKey("ItemCategory")] 
    public string CatID { get; set; } 

    public virtual ItemCategory ItemCategory { get; set; }   
} 

public class ItemCategory 
{ 
    // This should be the identity index 
    public int ItemCategoryID { get; set; } 

    // This should be the foreign key 
    public string CatID { get; set; } 

    public string Name { get; set; } 

    public virtual ICollection<Item> Items { get; set; } 
} 

我看到這個answer - 我應該配置我的表使用模型構建器?

回答

1

Item中的外鍵必須指向ItemCategory中的主鍵。 EF中的FK行爲與數據庫中的行爲完全相同。這意味着FK必須指向主體中具有唯一值的財產。問題在於EF不支持唯一索引/約束,因此實現唯一性的唯一方法是主鍵。

因此,你不能指向你的FK到CatID,除非它是主鍵的一部分,但在這種情況下,您將有一個包含複合鍵都ItemCategoryIDCatID和你的項目的類必須同時包含他們形成正確的FK 。

+0

我沒有使用int索引,只是使用字符串作爲鍵,因爲它更重要。無論如何謝謝@拉迪斯拉夫姆爾卡 – Ron

相關問題