从我的数据库上下文中删除基于id的用户

时间:2014-01-29 12:33:06

标签: asp.net-mvc asp.net-authentication

我正在尝试为用户实现基本的删除操作方法:

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

我不完全确定如何删除用户。

这是我到目前为止所尝试的:

  userDb.Users.Remove();  But now I don't know how to tell it to delete the user with a certain ID?

我该怎么做?

2 个答案:

答案 0 :(得分:2)

假设您的userDbDbContext(而不是ObjectContext),有几种方法可以实现您的目标。 您可以通过以下方式执行此操作:

var user = userDb.Users.FirstOrDefault(u => u.UserId == id);
if(user != null)
{
    userDb.Users.Remove(user); 
}

或者你可以这样做:

var user = userDb.Users.FirstOrDefault(u => u.UserId == id);
if(user != null)
{
    userDb.Entry(user).State= EntityState.Deleted;
    userDb.SaveChanges();
}

答案 1 :(得分:0)

查看本教程 - Remove Entity in Entity Framework

教程中的示例代码 -

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