lundi 19 octobre 2015

Entity Framework 6 and SQLite - cannot create entry with PK of entry deleted before

I'm using the Entity Framework 6 and the SQLite database (System.Data.SQLite.EF6), but I cannot create an entry with same primary key instantly after deleting it. For example:

My model of entity:

public class Person
{
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.None)]
  public int Id { get; set; }

  public int Name { get; set; }
}

STEPS:

1) I insert the instance of this entity person1 (with Id = 1) into my table of persons.

using (var context = new MyDbContext())
{
   context.Create(person1);
   await context.SaveChangesAsync();
}

2) Afters some tome I clear the entire Persons table with:

using (var context = new MyDbContext())
{
   await context.Database.ExecuteSqlCommandAsync(string.Format("DELETE FROM `PersonModels`"));
   await context.SaveChangesAsync();
}

3) I try to add entry with same primary key as entry from 1st step: person1 (with Id = 1)

using (var context = new MyDbContext())
{
   context.Create(person2);
   await context.SaveChangesAsync();
}

But in 3rd step, SaveChangesAsync() fails with

System.InvalidOperationException: The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: Saving or accepting changes failed because more than one entity of type 'DbModels.PersonModel' have the same primary key value.

When I add some other entry after clearing the table (with different primary key) and then add entry from 1st step, it works fine and both entries are saved without exceptions.

I added a breakpoint directly before creating of a new entry (after table is cleared) and checked the Persons table by external tool and table is empty (so there is no entry with id = 1).

Aucun commentaire:

Enregistrer un commentaire