简体   繁体   中英

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

I need to delete a row using ado.net entity data model. Already googling about this, but i still can't find out how to do it right.

Here's my code:

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

You can use

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");

I make a public class named Session

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

and changed my code into

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM