Add, Update and Delete Objects in Entity Framework 4.0

Posted by: Suprotim Agarwal , on 12/11/2010, in Category Entity Framework
Views: 703905
Abstract: In this article, we will see how to Add, Update and Delete objects in our conceptual Entity model and push the changes to the underlying database.

In a previous article, we saw how to Create an Entity Framework Model and Use it in Multiple Projects. In this article, we will see how to Add, Update and Delete objects in our conceptual model and push the changes to the underlying database.


We will be using the same console application that we created in the previous article, so make sure you have read the previous article before we continue. We will be adding three methods to the console application: addCustomer(), deleteCustomer() and modifyCustomer()

Create and Add Objects in Entity Framework 4.0

In order to add new objects to the Entity Set, you must create an instance of an Entity type and add the object to the object context. Objects attached to the object context are managed by that object context. Now there are three ways to add a new object to the object context:

1. Use ObjectSet<TEntity>.AddObject()
2. Use ObjectContext.AddObject()
3. Use EntityCollection<TEntity>.Add()

We will be using the first method i.e. ObjectSet<TEntity>.AddObject(). Observe the code shown below:
EF4 Add Entity

All we are doing here is create a new instance of the Customer type and populate its properties. We then add this instance to the Customers set using the EntitySet<T>.AddObject method. The AddObject() method is used for adding newly created objects that do not exist in the database. When AddObject() is called, a temporary EntityKey is generated and the EntityState is set to 'Added', as shown below:
Entity State Added

When context.SaveChanges() is called, EF 4.0 goes ahead and inserts the record into the database. Note that Entity Framework converts our code into queries that the database understand and handles all data interaction and low-level details. Also notice in the code above, that we are accessing data as objects and properties.


After you have executed the code, you can go ahead and physically verify the record in the database. If the query executed successfully, you should see a new record in the Customers table of the Northwind database, as shown below:
Entity Added In DB

Update Objects in Entity Framework 4.0

As I mentioned earlier, objects attached to the object context are managed by that object context. The steps to update an existing entity are quite simple. First retrieve an instance of the entity from the EntitySet<T> (in our case ObjectSet<Customer>), then edit the properties of the Entity and finally call SaveChanges() on the context.
EF4 Update Entity

In the code shown above, we are modifying the newly inserted record (‘ID=DNC’) we created in the previous step and then add the ‘CEO’ value for the ContactTitle column. When EF converts your code to a SQL query, it automatically uses parameters to avoid SQL injection attacks.

Execute the code and go ahead and check the record in the database:
Entity Update In DB

Delete Objects in Entity Framework 4.0

To delete an existing record, retrieve an instance of the entity from the EntitySet<T> (in our case ObjectSet<Customer>), then call the ObjectSet<TEntity>.DeleteObject() . When the DeleteObject() method is called, the EntityState of the object is set to ‘Deleted’
Entity State Deleted

Finally call SaveChanges() on the context to delete the data from the data source. Another way to delete an object is to use the ObjectContext.DeleteObject() but we have used the ObjectSet.DeleteObject for our example
EF4 Delete Entity
Go ahead and check the database and you will find that the CustomerID=DNC no more exists.

Well this was an overview of how we can Add, Delete and Update Objects in Entity Framework 4.0. We have not yet touched upon issues like Concurrency, ForeignKey Dependencies and Cascading Deletes, which is common while dealing with CRUD operations. I will be covering that in my future articles.

If you are interested in Entity Framework 4.0, I strongly suggest you to check out my Entity Framework 4.0 article series.

The entire source code of this article can be downloaded over here.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Julian B on Wednesday, December 15, 2010 7:09 PM
I love your writing style suprotim. thanks i look ahead for more articles
Comment posted by nilesh on Friday, December 24, 2010 6:27 AM
I read all your articles on EF 4.0 till date. They are excellent. I am looking forward for more articles which cover concurrency, transaction, would like to know how a EDM pointing to SQL server can be easily point to Oracle.
Comment posted by John W on Wednesday, January 26, 2011 5:35 PM
Thank you so much for this excellent, to the point and for a beginner very understandable article. Been googling for quite a while to find a good example of how to perform simple updates with EF 4. Told myself i couldnt go to bed before i got this updatemethod working... and thanks to you now i can finally go to bed.Thanks again!!
Comment posted by Ivan Stefanov on Tuesday, April 26, 2011 11:19 AM
Simple and clear. Just Perfect! 10x a lot. This tutorial helped me to finish my stuff after whole day searching in internet. Have a virtual beer from me!
Comment posted by yogendra on Tuesday, September 13, 2011 12:34 PM
At the time of submitchanges on add new record, getting unhandled exception and validation, i under stand there some mismatch in datatype of column buts how i can debug it or how get the final sql statment
Comment posted by yogendra on Tuesday, September 13, 2011 1:15 PM
At the time of submitchanges on add new record, getting unhandled exception and validation, i under stand there some mismatch in datatype of column buts how i can debug it or how get the final sql statment
Comment posted by ricardo santana on Tuesday, October 18, 2011 2:01 PM
"An error occurred while updating the entries. See the inner exception for details."

What can be? and How to Fix?

Thank you.
Comment posted by Mrunal Buch on Friday, January 6, 2012 3:11 AM
what about updating the object graph or Related entities ?
Comment posted by Dina on Wednesday, May 2, 2012 4:23 PM
When I deployed my code to Integration Server or even copied entire solution to Integration Server, I get error on SaveChanges:
"An error occurred while updating the entries. See the inner exception for
But, I did not get such error when I test the same code locally.
What could be difference between local host and Integration Server
Comment posted by Soumen Roy on Friday, July 27, 2012 2:10 AM
Nice post. Thanks for sharing it.
Comment posted by Anjum Rizwi on Thursday, August 9, 2012 5:41 AM
Very good article.
It helped me to start using EF.

one question: How to truncate table using EF?
Comment posted by Julio Veloz on Tuesday, September 4, 2012 6:52 PM
I would like to know how to work with two or more entities at the same time and how to update when one depends from the other, e.g. the balance of an account when I register a deposit?
Comment posted by LT on Thursday, September 20, 2012 11:37 AM
I would like to know how to perform the update operation by passing in a populated Customer object that is NOT from context and assigning it's properties to the Customer object that IS in context.

So a user could update a customer form on a web page and upon posting the web form, that customer object gets carried to your update example above and saved to the context.

How do I do this?
Comment posted by Rameshkumar on Wednesday, November 28, 2012 11:58 PM
customerid integer,
userid integer,
DOB timestamp

userid integer,
username varchar(100),
password varchar(100),
firstname varchar(50),
lastname varchar(50),
email varchar(100),
isactive bit

For username and password are updated on new mode.

The following statement to used to update on edit mode, but i am getting exception

Customer editCustomer = DB.Customers.First(c => c.customerid == customerId);
if (editCustomer != null)
   User editUser = DB.Users.First(u => u.userid == editCustomer.User.userid);
   if (editUser != null)
      editUser.firstname = userData.firstname;
      editUser.lastname = userData.lastname; =;
      editUser.isactive = userData.isactive;
   customerData.User = editUser;
   editCustomer = customerData;
Comment posted by nikita on Wednesday, December 19, 2012 9:48 PM
it's really very usable article. Thank you.
Comment posted by gfhfhgfhg on Saturday, March 2, 2013 4:55 AM
hffghfhfghfsdfs sdfsdf sdfsdf
Comment posted by josh on Monday, March 4, 2013 8:41 AM
great article made everything "click"!
Comment posted by Med Amine on Tuesday, March 5, 2013 5:54 PM
Great article but i was wondering if it is possible to implement crud methods using wcf services!!
if it is possible is there any good tutorials on this subject
ps: thanks again for the article it was very helpful
Comment posted by Ric P on Tuesday, March 19, 2013 9:59 AM
Nice article!
Comment posted by 56565 on Tuesday, April 30, 2013 2:25 AM
Comment posted by fadwa on Thursday, May 2, 2013 3:17 AM
Hello, I have a problem with the function of suppression,
I have a category table and I wanted to delete a record with id of the category given parameters of the function,
but it gives me this error "An unhandled exception of type 'System.Data.UpdateException' occurred in System.Data.Entity.dll "
showing the ab.SaveChanges line ();

    public void Delete(int id)
            GooglaOneErpEntities3 ab = new GooglaOneErpEntities3();
            var cat = ab.CategorieProduit.First(m => m.IdCategorieProduit == id);

            // Suppression

Comment posted by TAN TH on Thursday, June 6, 2013 3:01 AM
hi thanks for the nice article... it is good information.
I try out with, not with Console, but with WPF, Add New Item, ADO.NET Entity Data Model, then link to Northwind database, I am using EF 5.0.0.

I could not could through this code:
in public static void addCustomer(NorthwindEntities context)
but can only have context.Customers.Add(cust); which is able to compile through, but enter errors when run.
Could you help me via email?

I run your console application, there is no error, it is able to add new customer to the database. I believe my WPF should work too.

Comment posted by Priyanshu on Sunday, June 16, 2013 11:47 PM
Very - 2 nice Article written by you. i really appreciate you for this work.
Comment posted by Sarasa on Tuesday, June 25, 2013 6:52 AM
InvDepartment invDepartment = new InvDepartment();
            InvDepartmentService invDepartmentService = new InvDepartmentService();
            if (existingDeparment!=null && existingDeparment.InvDepartmentID != 0)
                invDepartment = invDepartmentService.GetInvDepartmentByCode(txtDepartmentCode.Text.Trim());
            invDepartment.GroupOfCompanyID = 102;
            invDepartment.DepartmentCode = txtDepartmentCode.Text.Trim();
            invDepartment.DepartmentName = txtDepartmentDescription.Text.Trim();
            invDepartment.Remark = txtRemarks.Text.Trim();

            if (invDepartment.InvDepartmentID==0)
Comment posted by rakesh on Tuesday, July 16, 2013 3:33 AM
context.SaveChanges() not work how to use it
error update/insert function not define
please reply
Comment posted by Anup on Wednesday, December 11, 2013 2:13 AM
Thanks :)
Comment posted by Meenakshi on Tuesday, January 28, 2014 7:01 AM
Good and helpful article . Thanks !
Comment posted by pranitha on Tuesday, February 25, 2014 10:28 AM
thank you very much this info was great
Comment posted by 12345 on Monday, March 24, 2014 6:15 AM
Comment posted by ghfjhg on Monday, April 28, 2014 11:01 PM
Comment posted by kishor karpe on Monday, June 9, 2014 7:42 AM

  intellisense  not showing DeleteObject() method  when im trying to delete  
  the records pls reply .Thnks in advance
Comment posted by Rangler on Tuesday, December 23, 2014 12:09 AM