代码优先数据库:SqlException:违反 PRIMARY KEY 约束 'PK_dbo.PrivatKasses'。

code first database : SqlException: Violation of PRIMARY KEY constraint 'PK_dbo.PrivatKasses'.

我有这样一个模型:

class PrivatKasse
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int ID { get; set; }
    public decimal Betrag { get; set; }
    public int BenutzerID { get; set; }

}

和一个检查 table 是否为空的函数。如果是,函数会添加新行。函数:

public static void DatabaseChecker()
    {
        using (var _db = new DataContext())
        {
            if (!_db.KasseGemeinsam.Any())
            {
                _db.KasseGemeinsam.Add(new Models.Data.KasseGemeinsamModel() { Jahr = DateTime.Now.Year.ToString(), Monat = MonatenVertauchen.ZahlZuMonaten(Convert.ToInt32(DateTime.Now.Month)), Haushalt = 0, Hygine = 0, Mobel = 0, Nahrung = 0, Schreibware = 0, Sonstiges = 0 });
                _db.SaveChanges();
            }

            if (!_db.KassePrivat.Any())
            {
                _db.KassePrivat.Add(new Models.Data.KassePrivatModel() { Jahr = DateTime.Now.Year.ToString(), Monat = MonatenVertauchen.ZahlZuMonaten(Convert.ToInt32(DateTime.Now.Month)), UserID = UserIdentity.UserID, Fahrkosten = 0, Hygine = 0, Mobel = 0, Nahrung = 0, Schreibware = 0, Sonstiges = 0 });
                _db.SaveChanges();
            }

            if (!_db.GemeinsamKasse.Any())
            {
                _db.GemeinsamKasse.Add(new Models.Data.GemeinsamKasse() { Betrag = 0 });
                _db.SaveChanges();
            }

            if (!_db.PrivatKasse.Any())
            {
                List<int> userIDs = new List<int>();
                foreach (var item in _db.UsersTbl)
                {
                    userIDs.Add(item.ID);
                }
                using (var _db2 = new DataContext())
                {
                    foreach (var item in userIDs)
                    {
                        _db2.PrivatKasse.Add(new Models.Data.PrivatKasse() { BenutzerID = item, Betrag = 0 });

                    }
                    _db2.SaveChanges();
                }



            }


        }

但是我得到一个 SqlExeption:

System.Data.Entity.Infrastructure.DbUpdateException: "An error occurred while updating the entries. See the inner exception for details."

UpdateException: An error occurred while updating the entries. See the inner exception for details.

SqlException: Violation of PRIMARY KEY constraint 'PK_dbo.PrivatKasses'. Cannot insert duplicate key in object 'dbo.PrivatKasses'. The duplicate key value is (0).

The statement has been terminated.

我该如何解决这个问题?

我认为问题是因为您在声明

后没有提供 ID(int 中的默认值为 0)
[DatabaseGenerated(DatabaseGeneratedOption.None)]

这意味着数据库不会创建id,我建议改用Identity

[DatabaseGenerated(DatabaseGeneratedOption.Identity )]

那么你应该可以使用

_db2.PrivatKasse.Add(new Models.Data.PrivatKasse() { BenutzerID = item, Betrag = 0 })

否则提供 id

_db2.PrivatKasse.Add(new Models.Data.PrivatKasse() {ID= customID, BenutzerID = item, Betrag = 0 })