Abort due to constraint violation PRIMARY KEY must be unique

记录SQLite唯一主键的错误及解决方法,错误如标题中所示,违反了主键唯一性约束。

简单设计表结构如下(Students):

Abort due to constraint violation PRIMARY KEY must be unique_第1张图片

Id:integer primary key

在执行

SchoolEntities school = new SchoolEntities();

school.Students.AddObject(new Student { Name = "Tom" });
school.Students.AddObject(new Student { Name = "Jane" });
school.Students.AddObject(new Student { Name = "Rose" });
school.Students.AddObject(new Student { Name = "Maya" });
school.Students.AddObject(new Student { Name = "Maly" });
school.Students.AddObject(new Student { Name = "Marry" });
school.Students.AddObject(new Student { Name = "King" });
school.Students.AddObject(new Student { Name = "Jill" });
school.SaveChanges();

但在执行的时候出错以下错误:

Abort due to constraint violation PRIMARY KEY must be unique_第2张图片

解决方法如下:

1. 为每一个实体的Id提供不同的值

2. 在创建Id列时候设置为:INTEGER PRIMARY KEY AUTOINCREMENT

3. 手动更改Edmx(SSDL)文件,设置为:

  
  
< Property Name ="Id" Type ="integer" Nullable ="false" StoreGeneratedPattern ="Identity" />

你可能感兴趣的:(CONSTRAINT)