EF Core removerange items not removed on transaction

c# entity-framework entity-framework-core sqlite uwp

Question

Here's my prblem

using (var db = new CassaContext()) {        
      var DbSet = db.GetByName(item.Name);
      DbSet.RemoveRange(DbSet);

      for (var i = 0; i < data.Count; i++)
      {
           JObject jitem = data[i] as JObject;
           var dbobj = vm.Db.JsonToObject(jitem);             
           DbSet.Add(dbobj);
       }

       db.SaveChanges();
}

If i will add db.SaveChanges() after the RemoveRange() istruction, everything is fine, but, without that, i have the error

The instance of entity type 'Users' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.

I would like to avoid saving after the removerange, because i won't have empty tables if the transaction fails.

How can i solve this? Thanks in advance! If you need more just ask!

1
0
7/28/2016 5:41:33 PM

Popular Answer

Not sure about this error, but you could try using an explicit transaction:

using (var db = new CassaContext())
using (var transaction = db.Database.BeginTransaction())
{
    var DbSet = db.GetByName(item.Name);
    DbSet.RemoveRange(DbSet);
    db.SaveChanges();

    for (var i = 0; i < data.Count; i++)
    {
        JObject jitem = data[i] as JObject;
        var dbobj = vm.Db.JsonToObject(jitem);             
        DbSet.Add(dbobj);
    }
    db.SaveChanges();

    transaction.Commit();
}
2
7/28/2016 8:50:36 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow