Question

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?

Was it helpful?

Solution

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

OTHER TIPS

Check out this tutorial - Remove Entity in Entity Framework

Sample code from tutorial -

  using (var dbCtx = new SchoolDBEntities())
        {

            //if already loaded in existing DBContext then use Set().Remove(entity) to delete it.
            var newtchr = dbCtx.Teachers.Where(t => t.TeacherName == "New teacher4")
                                .FirstOrDefault<Teacher>();
            dbCtx.Set(Teacher).Remove(newtchr);

            //Also, you can mark an entity as deleted
            //dbCtx.Entry(tchr).State = System.Data.EntityState.Deleted;    

            //if not loaded in existing DBContext then use following.
            //dbCtx.Teachers.Remove(newtchr);

            dbCtx.SaveChanges();
        } 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top