违反PRIMARY KEY约束。无法在对象中插入重复键(更新如何存在行)

时间:2019-06-21 08:04:13

标签: c# sql entity-framework entity

我有一个模型类ProfileDbContext

public class UserContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Profile> Profiles { get; set; }
    public UserContext() : base("name=UserContext") { }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<UserContext, MigrateDBConfiguration>());
    }
}

public class Profile
{
    [Key]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    [JsonProperty("pk")]
    public long User_Id { get; set; }
    public string username { get; set; }

    [Column("Follower_Id")]
    public ICollection<Profile> Followers { get; set; }

    [Column("Following_Id")]
    public ICollection<Profile> Following { get; set; }
}

当我运行此代码时:

using (UserContext db = new UserContext())
{
    User = db.Users.FirstOrDefault(e => e.Profile.User_Id.Equals(User_Id));

    var profile = (await GetUserInfo(User_Id)).GetResult();
    await GetUserFollowing(profile);
    await GetUserFollowers(profile);

    if (User == null)
    {
        User = db.Users.Add(new User()
        {
            Profile = profile,
            UserName = login
        });                         
    }
    else
    {
        var p = db.Profiles
            .Include("Followers")
            .Include("Following")
            .FirstOrDefault(e => e.User_Id.Equals(User_Id));
        p.Followers = profile.Followers;
        p.Following = profile.Following;    
        User.Profile = p;
    }

    await db.SaveChangesAsync();
}

我收到此错误:

  

违反主键约束'PK_dbo.Profiles'。无法在对象“ dbo.Profiles”中插入重复密钥。重复的键值为(856399)。

1 个答案:

答案 0 :(得分:0)

使用此属性:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

还将表主键列属性标识规范更改为

enter image description here