2015-04-26 34 views
0

添加一個外鍵Id屬性我有兩個類我需要在MVC模型的代碼首先

public class Shop 
{ 
    public int Id { get; set;} 
    public string Name { get; set;} 

    public virtual ICollection<Product> Products { get; set; } 
} 

public class Product 
{ 
    public int Id { get; set;} 

    public virtual Shop Shop {get;set;} 

    //Do i need this line as well? 
    public int ShopId {get;set;} 
} 

我的問題是,我需要定義ShopId?我看到很多代碼示例,有時它在那裏,有時不是。

回答

0

您不需要使用ShopId屬性作爲外鍵。但是,如果您不添加ShopId,Enitiy Framework本身會創建一個名爲TableName_TableEntityId的外鍵屬性。

0

一個可以有很多產品類有一個列表 屬性,讓你在某家商店訪問這些產品。此外,產品類別具有Shop屬性,因此您可以看到Shop與特定的產品相關聯。代碼首先認識到這一點一個一對多的關係之間的產品和,按照慣例,確定產品表將需要爲了一個外鍵,堅持自己的知識,其中一個產品屬於。 Code First使用模式[Name of navigation property]_[Primary Key of related class](即, Shop_ShopId)在數據庫中創建外鍵。並且感謝一些額外的元數據Code First built,Entity Framework將知道使用外鍵查詢或 保存到數據庫。

public class Shop 
{ 
    public int ShopId { get; set;} 
    public string Name { get; set;} 

    public virtual ICollection<Product> Products { get; set; } 
} 

public class Product 
{ 
    public int Id { get; set;} 

    public virtual Shop Shop {get;set;} 

}