Search code examples
c#linqado.net-entity-data-model

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

Solution

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