Asp.net mvc 表具有主键,因为当首先在实体框架代码中为两个外键插入相同的值时,两个外键引发异常

Asp.net mvc 表具有主键,因为当首先在实体框架代码中为两个外键插入相同的值时,两个外键引发异常,asp.net-mvc,entity-framework,Asp.net Mvc,Entity Framework,我有三张桌子: tbl.属性: tbl.产品: tbl.ProductAttribute: 当我为2个外键同时插入具有相同值的tbl.ProductAttribute时,它会引发一个异常: 我刚刚想到了一种解决方法,在tbl.ProductAttribute中插入一个新列 然后将其设置为主键,并使用ProductId、AttributeId作为外键。但这是解决这个问题的方法吗?如果是,有没有更好的方法可以在不更改代码的情况下解决此问题?主键需要是表行的唯一标识符。如果共享密钥有重复项,则它不能

我有三张桌子:

tbl.属性:

tbl.产品:

tbl.ProductAttribute:

当我为2个外键同时插入具有相同值的tbl.ProductAttribute时,它会引发一个异常:

我刚刚想到了一种解决方法,在tbl.ProductAttribute中插入一个新列


然后将其设置为主键,并使用ProductId、AttributeId作为外键。但这是解决这个问题的方法吗?如果是,有没有更好的方法可以在不更改代码的情况下解决此问题?

主键需要是表行的唯一标识符。如果共享密钥有重复项,则它不能是主键。只需为行标识添加另一列,并根据需要增加它或生成guid。您可以为外键创建非唯一索引,以帮助运行联接时提高性能。

您的ProductAttribute表是多对多联接表,其中ProductId和AttributeId是该表的复合主键。所以ProductId和AttributeId的集合必须是唯一的,因为主键不能重复。如果要为ProductId和AttributeId集插入重复的值,则ProductAttribute模型类应如下所示:

public class ProductAttribute 
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public long ProductAttributeId { get; set;}

   public int ProductId  { get; set;}

   public int AttributeId  { get; set;}

   public string Value  { get; set;}
}
public class ProductAttribute 
{
    [Key, Column(Order = 0)]
    public int ProductId  { get; set;}

    [Key, Column(Order = 1)]
    public int AttributeId  { get; set;}

    [Key, Column(Order = 2)]
    public string Value  { get; set;}
}
此外,如果您想要ProductId、AttributeId的集合可以重复,但是ProductId、AttributeId和Value的集合应该是唯一的,那么您的ProductAttribute模型类应该如下所示:

public class ProductAttribute 
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public long ProductAttributeId { get; set;}

   public int ProductId  { get; set;}

   public int AttributeId  { get; set;}

   public string Value  { get; set;}
}
public class ProductAttribute 
{
    [Key, Column(Order = 0)]
    public int ProductId  { get; set;}

    [Key, Column(Order = 1)]
    public int AttributeId  { get; set;}

    [Key, Column(Order = 2)]
    public string Value  { get; set;}
}

请始终尝试将信息添加为文本,而不是图像。它使回答者更容易将部分内容复制/粘贴到答案中。此外,如果没有看到导致问题的代码,大多数问题都无法回答。
public class ProductAttribute 
{
   [Key]
   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   public long ProductAttributeId { get; set;}

   public int ProductId  { get; set;}

   public int AttributeId  { get; set;}

   public string Value  { get; set;}
}
public class ProductAttribute 
{
    [Key, Column(Order = 0)]
    public int ProductId  { get; set;}

    [Key, Column(Order = 1)]
    public int AttributeId  { get; set;}

    [Key, Column(Order = 2)]
    public string Value  { get; set;}
}