[英]Foreign key mvc 4 code first c#
How can i add a foreign key to a Model (code first) 如何将外键添加到模型(先编码)
i have a model Product which has an ID (primary key) which i want to add to my model order like. 我有一个模型产品,该产品具有要添加到我的模型订单中的ID(主键)。
public class Order
{
public int ID {get; set;}
[Required]
public int Total {get; set;}
[Required]
public int ProductId{get; set;}
}
but how can i make the ProductId refer to the id of my Product model like a foreign key? 但是如何使ProductId像外键一样引用我的产品模型的ID? On Stackoverflow there are alot simmilar questions but all with different answers, but they arent working for me.
在Stackoverflow上有很多类似的问题,但是所有问题都有不同的答案,但是它们并没有为我工作。 I really hope someone has a solution or can points me in the right direction with an explanation.
我真的希望有人能提供解决方案,或者可以向我指出正确的方向并提供解释。
You need to add a navigation property: 您需要添加导航属性:
public virtual Product Product { get; set; }
So the Order class will look like this: 因此,Order类将如下所示:
public class Order
{
public int ID {get; set;}
[Required]
public int Total {get; set;}
[Required]
public int ProductId{get; set;}
[Required]
public virtual Product Product { get; set; }
}
Also, strictly speaking the ProductId
property isn't needed once you have the virtual Product property. 另外,严格来说,一旦拥有虚拟Product属性,就不需要
ProductId
属性。
You could do something like this: 您可以执行以下操作:
public class Order
{
public int ID {get; set;}
[Required]
public int Total {get; set;}
[Required]
public int ProductId{get; set;}
[ForeignKey("ProductId")]
public virtual Product Product {get; set;}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.