alphamalle alphamalle - 1 year ago 153
SQL Question

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 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.Entry(user).State = EntityState.Modified;

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

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download