Skip to content
Advertisement

Can’t delete a row using entity framework

The problem that I’m having is that I can’t delete a row when using entity. I’m able to find the row, but the error I get the next error:

Additional information: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.

I tried updating the database in the package manager console, I tried several different ways of deleting the record, but no luck by the moment. Auto Migrations are enabled.

Below is the code I am currently trying to use.

   var ctx = new Context();
   ApplicationUser user = new ApplicationUser { UserName = myUsername };
   ctx.Users.Attach(user);
   ctx.Users.Remove(user);
   ctx.Entry(user).State = EntityState.Modified;
   ctx.SaveChanges();

All help is appreciated. I have been banging my head on this for hours.

Advertisement

Answer

The common way to remove entity in EF is the following:

  • locate entity using DbSet<T>. This could be retrieving entity from set or attaching it to the set;
  • call DbSet<T>.Remove;
  • call DbContext.SaveChanges.

Since ApplicationUser.UserName is not a primary key property, you need to find entity. Attaching doesn’t make sense here – DbSet<T>.Attach tells context to treat entity with given primary key as existing and non-modified, but you don’t set primary key value (probably, it is generated in constructor, since you’re using GUIDs?).

Something like this:

// assuming, that user names are not unique
var user = ctx.Users.FirstOrDefault(_ => _.UserName == myUsername);
if (user != null)
{
    ctx.Users.Remove(user);
    cts.SaveChanges();
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement