实体框架核心:违反PRIMARY KEY约束无法在对象中插入重复的密钥

时间:2019-05-07 04:47:46

标签: c# entity-framework asp.net-core entity-framework-core

将记录插入子表中时出现以下错误,为什么当我要求实体框架将记录插入子表(关键字)时,Entity Framework Core试图将记录插入父表(IdentityUser表)中表)?

StackTrace:

An unhandled exception occurred while processing the request.
SqlException: Violation of PRIMARY KEY constraint 'PK_IdentityUser'. Cannot insert duplicate key in object 'dbo.IdentityUser'. The duplicate key value is (39b72c3a-b5bf-43e4-84f9-5cddbe79f6e3).
The statement has been terminated.

型号:

public class Keyword
  {
    public Keyword() { }
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int KeywordId { get; set; }
    public IdentityUser User { get; set; }
    public string Value { get; set; }
    [Timestamp]
    public byte[] RowVersion { get; set; }
  }

将记录保存到“关键字”表的代码:

    var keywords = new List<Keyword>();
var identityUser = await UserManager.GetUserAsync(User);
              foreach (var keywordString in keywordsThatNeedToBeSaved)
              {
                keywords.Add(new Keyword()
                {
                  User = identityUser,
                  Value = keywordString
                });
              }
              ScrubberDbContext.Keywords.AddRange(keywords);
                await ScrubberDbContext.SaveChangesAsync();

enter image description here enter image description here enter image description here

2 个答案:

答案 0 :(得分:5)

将关键字类别更改为:

public class Keyword
    {
        public Keyword() { }
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int KeywordId { get; set; }
        public int? UserId { get; set; }
        [ForeignKey("UserId")]
        public IdentityUser User { get; set; }
        public string Value { get; set; }
        [Timestamp]
        public byte[] RowVersion { get; set; }
    }

并将保存记录更改为:

var keywords = new List<Keyword>();
 var identityUser = await UserManager.GetUserAsync(User);
              foreach (var keywordString in keywordsThatNeedToBeSaved)
              {
                keywords.Add(new Keyword()
                {
                  UserId = identityUser.Id,
                  Value = keywordString
                });
              }
              ScrubberDbContext.Keywords.AddRange(keywords);
                await ScrubberDbContext.SaveChangesAsync();

答案 1 :(得分:0)

似乎您不是通过EF获取用户。

这样,EF无法看到它的来源,并试图插入一个新的。

您可以按ID引用它,也可以通过DbContext获取它。