I am trying to implement the basic delete action method for a user:
private User_Manager_Interface.Models.ApplicationDbContext userDb = new User_Manager_Interface.Models.ApplicationDbContext();
// POST: /Users/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
//.Remove(u => u.id == id);
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I am not entirely sure how to delete a user.
This is what I have tried so far:
userDb.Users.Remove(); But now I don't know how to tell it to delete the user with a certain ID?
How do I do this?
Assuming that your userDb
is DbContext
(not an ObjectContext
) there are a few ways to achieve your goal.
You can do this in the following way:
var user = userDb.Users.FirstOrDefault(u => u.UserId == id);
if(user != null)
{
userDb.Users.Remove(user);
}
Or you could do this:
var user = userDb.Users.FirstOrDefault(u => u.UserId == id);
if(user != null)
{
userDb.Entry(user).State= EntityState.Deleted;
userDb.SaveChanges();
}