I have a problem with Entity Framework and Code First. I have an entity with the Timestamp property, and I add a new record to the database, call SaveChanges, and everything is fine. When I try to delete the entry I just added, I get the following message:
Save expression about updating, insertion or deletion caused by an unexpected number of rows (0). Objects can be modified or deleted as objects are loaded. Update ObjectStateManager Records.
It seems to me that EF does not know that this new record exists in the database, despite the fact that it exists. Sometimes, even when I try to update another record, I get the same message, but if I try to delete another, it will work.
Does anyone know why this is happening?
Thanks in advance, Diego
EDIT I compiled some code to make it easier to understand my problem:
I have two simple objects:
public class Entidade1 { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int ID { get; set; } public string Descricao { get; set; } [Timestamp] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public byte[] RecTS { get; set; } } public class Entidade2 { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int ID { get; set; } public string Descricao { get; set; } [Timestamp] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public byte[] RecTS { get; set; } public virtual Entidade1 Entidade1 { get; set; } }
Context:
public class DB : DbContext { public DB() : base("DB") { this.Configuration.AutoDetectChangesEnabled = true; this.Configuration.LazyLoadingEnabled = true; this.Configuration.ProxyCreationEnabled = true; } public DbSet<Entidade1> Entidade1 { get; set; } public DbSet<Entidade2> Entidade2 { get; set; } }
And the code:
var item = new Entidade1 ();
item.Descricao = "teste"; var db = new DB(); db.Set(typeof(Entidade1)).Add(item); db.SaveChanges(); var item2 = new Entidade2(); item2.Descricao = "teste 2"; item2.Entidade1 = item; db.Set(typeof (Entidade2)).Add(item2); db.SaveChanges(); var q = (from c in db.Entidade1 where c.Descricao == "teste" select c).FirstOrDefault(); db.Set(typeof(Entidade1)).Remove(q); db.SaveChanges(); var q2 = (from c in db.Entidade2 where c.Descricao == "teste 2" select c).FirstOrDefault(); db.Set(typeof (Entidade2)).Remove(q2); db.SaveChanges();