Reputation: 1114
First of all, I'm a just beginner, when I trying to delete a record in sql by passing id through view to controller, below is my code:
Note: 'username' is the PK in table "T_Users"
#region Delete record function
public ActionResult Delete(string id ) {
T_Users temp_u = new T_Users() { Username = id };
//db.T_Users.Attach(new T_Users() { Username = id });
db.T_Users.Remove(temp_u);
try
{
db.SaveChanges();
//return View();
}
catch(Exception e) {
return Content("hehe");
}
return RedirectToAction("Index");
}
#endregion
When I call the T_Users.Attach() method, it said "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key"
Then I commented that, it failed because "The object cannot be deleted because it was not found in the ObjectStateManager."
Can anybody offer some ideas about the solution?
Upvotes: 0
Views: 1875
Reputation: 1
Hi first of all you should get the user form its model ( that is connected to database ) eg : ur model name is User (the _context is the Implementation of data base context eg : i have a database context which name is ShopContext, in ShopContext i have
public class ShopContext : DbContext
{
public DbSet<User> Users { get; set; }
public ShopContext(DbContextOptions<ShopContext> options) : base(options)
{
}
}
deleted User :
private readonly ShopContext _context;
public AdminService(ShopContext context)
{
_context = context;
}
first we inject codes like above then we can create method to delete a use by id
public void deleteUserById(int id)
{
User user = _context.Users.Find(id);
_context.Users.Remove(user);
_context.SaveChanges()
}
Upvotes: 0
Reputation: 22016
you are not retrieving the object from the data context before attempting to delete it, instead you are creating a new detached object assigning the same id as an existing one and attempting to delete it.
You should first retrieve the object you wish to delete from the data context then issue the delete command on the retrieved object. This is an ORM, so you are not simply generating SQL to execute but managing mapped objects.
I hope this helps.
Not a big EF user but you can do something like this with it:
var user = db.T_Users.First(e => e.Username == id);
db.T_Users.Delete(user);
There a a load of EF tutorials like this out there though:
http://www.codeproject.com/Articles/37932/Simple-Sample-with-Entity-Framework
Upvotes: 2