我是否需要首先在mvc模型代码上添加外键Id属性

时间:2015-04-26 14:23:53

标签: asp.net-mvc entity-framework

我有两个班级

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?我看到很多代码样本,有时它就在那里,有时它不是。

2 个答案:

答案 0 :(得分:0)

您不需要将ShopId属性用于外键。但是如果你不添加ShopId,Enitiy Framework本身就会创建一个名为TableName_TableEntityId的外键属性。

答案 1 :(得分:0)

商店可以有多个商品,而商店类有一个列表 允许您从特定商店访问产品的属性。此外,Product类具有Shop属性,因此您可以看到 Shop 与特定产品相关联的内容。 Code First在购物产品之间识别一对多关系,按照惯例,确定产品 table需要一个外键才能保持对商店所属的商店的了解。 Code First使用模式[Name of navigation property]_[Primary Key of related class]在数据库中创建外键(即, Shop_ShopId)。并且还要感谢Code First的一些额外元数据 在查询时,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;}

}