Category Archives: Entity Framework

How can we add, update and delete using EF?

Create the object of your entity class, add it to the data context using add object method and then call save changes method.

CustomermytestEntities obj = new CustomermytestEntities(); 
Customer objCust = new Customer(); 
objCust.CustomerCode = "1001"; 
obj.Customers.AddObject(objCust); 
obj.SaveChanges();

If you want to update , select the object , make change to the object and call accept changes.

CustomermytestEntities objContext = new CustomermytestEntities(); 
Customer objCustomer = (Customer)objContext.Customers.FirstOrDefault(); 
objCustomer.CountryCode = "NEP"; 
objContext.AcceptAllChanges();

If you want to delete call the delete object method as shown in the below code snippet.

CustomermytestEntities objContext = new CustomermytestEntities(); 
Customer objCustomer = (Customer)objContext.Customers.FirstOrDefault();
objContext.DeleteObject(objCustomer);