在 ado.net 实体数据模型中删除行的正确方法

Right way to delete a row in ado.net entity data model

我需要使用 ado.net 实体数据模型删除一行。已经在谷歌上搜索过了,但我仍然找不到正确的做法。

这是我的代码:

else if (mode == 3)
            {
                LaundryEntities1 db = new LaundryEntities1();
                var query = (from user in db.Users
                             where user.UserID == textBoxID.Text
                             select user).First();
                db.DeleteObject(query);
                db.SaveChanges();
                reload();
                MessageBox.Show("Succesfully delete a user");
                clear();
            }

您可以使用

LaundryEntities1 db = new LaundryEntities1();
            var query = (from user in db.Users
                         where user.UserID == textBoxID.Text
                         select user).First();

            db.Entry(employer).State = EntityState.Deleted

            if(db.SaveChanges())
              MessageBox.Show("Succesfully delete a user");

我创建了一个 public class 名为 Session

public class session
    {
        public static DatabaseEntities db = new DatabaseEntities();
        public static User user = null;
    }

并将我的代码更改为

Users user = (from x in session.db.Users
              where x.UserID == textBoxID.Text
              select x).FirstOrDefault();
session.db.Users.DeleteObject(user);
session.db.SaveChanges();