alphamalle alphamalle - 5 months ago 38
SQL Question

Can't delete a row using entitiy

The problem that I am having is that I can't delete a row when using entity. The record is found fine, but the error I get is


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 have tried updating the database in the package manager console, I have tried several different ways of deleting the record, but I have had no luck. 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.

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();
}