加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Entity Framework 6和SQLite – 无法创建具有之前删除的条

发布时间:2020-12-15 07:52:52 所属栏目:百科 来源:网络整理
导读:我正在使用Entity Framework 6和SQLite数据库(System.Data.SQLite.EF6),但删除后我无法立即创建具有相同主键的条目.例如: 我的实体模型: public class Person{ [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] public int Id { get; set; } publ
我正在使用Entity Framework 6和SQLite数据库(System.Data.SQLite.EF6),但删除后我无法立即创建具有相同主键的条目.例如:

我的实体模型:

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

  public int Name { get; set; }
}

脚步:

1)我将此实体person1的实例(Id = 1)插入到我的人员表中.

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

2)在一些书籍后,我用以下内容清除整个人员表:

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

3)我尝试添加与第一步中的条目相同的主键:person2(Id = 1)

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

但是在第3步中,SaveChangesAsync()失败了

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.

当我在清除表(使用不同的主键)之后添加一些其他条目然后从第1步添加条目时,它工作正常并且两个条目都保存,没有例外.

我在创建新条目之前直接添加了断点(在清除表之后)并通过外部工具检查了Persons表,并且表是空的(因此没有id = 1的条目).

更新:
我的Create方法的扩展DbContexte实现:

public DbSet<PersonModel> Persons { get; set; }

    public T Create<T>(T entity)
        where T : class
    {
        try
        {
            GetDbSetForType<T>().Add(entity);
            return entity;
        }
        catch (Exception ex)
        {
            return default(T);
        }
    }

    private DbSet<T> GetDbSetForType<T>()
        where T : class
    {
        var type = typeof(T);

        if (type == typeof(PersonModel)) return Persons as DbSet<T>;
        //...my other types
        throw new Exception("Type not found in db");
    }

解决方法

EF数据库上下文维护一个在数据库内存中检索的对象列表,直到它被销毁或卸载为止.
using (var ctx = new MyDbContext())
{
    var person1 = new Person { Id = 1 };
    ctx.Persons.Add(person1);
    await ctx.SaveChangesAsync();

    await context.Database.ExecuteSqlCommandAsync(string.Format("DELETE FROM `PersonModels`"));

    // This is the secret
    ((IObjectContextAdapter)ctx).ObjectContext.Detach(person1);

    ctx.Persons.Add(person1)
    await ctx.SaveChangesAsync();

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读