Monday, September 20, 2010

Entity Framework : Part 6 – Perform CRUD operations using Entity Framework 4

Background

This is the sixth part of the Entity Framework  4 learning series. Today I am going to demonstrate how to perform create new entities and persist them to the database, read data from existing entities, perform updates to the existing entities and delete the unwanted entities. These commonly used operations are collectively called CRUD which stands for Create, Read, Update and Delete.

The read part was covered in the earlier posts related to querying data and sorting as well. So I won’t go too much into those things again. I’ll try and cover the other 3 aspects in this post.

Pre-requisite

Like we did in the couple of last post, lets get started with the first step of generating the entity data model. If you are not aware of how to create the entity data model based on existing database, please follow the steps mentioned in the post here.

Since I am using the sample Northwind database i wouldn’t want to fiddle around too much with it. The best part is I can just replace the .mdf file which I have backed up to restore the database to its original state.For the purpose of this demo I’ll try to work mostly with a single entity and perform all operations on the same.

Perform Create and Read Operations Using Entity Framework 4

Lets start with one of the simplest entity in the entity model which is Employee. Although it has got many properties for the sake of this example I can populate only few of them and save the object in the database. Following is the code snippet I will use to do this.

            NORTHWNDEntities context = new NORTHWNDEntities();

 

            Employee latestEmployee = new Employee

                {

                    Address = "Bangalore",

                    BirthDate = DateTime.Today.AddYears(-30),

                    City = "Bangalore",

                    Country = "India",

                    FirstName = "Nilesh",

                    LastName = "Gule",

                    Title = "Mr",

                    TitleOfCourtesy = "Sir",

                    HireDate = DateTime.Today.AddYears(-3)

                };

 

            //add using AddToEmployees method

            context.AddToEmployees(latestEmployee);

 

            context.SaveChanges();



As usual we start off with an instance of ObjectContext which happens to be NORTHWNDEntities in our case. I create an instance of Employee and set the properties using object initializer syntax. Then I use the AddObject method on the Employees object set and pass it the new instance of Employee entity. Finally I save the changes to the database using SaveChanges method of the context.

If everything went fine we would have added the new customer to the database. But how do we verify that? We can query the employee instance above and check if the EmployeeID property has a valid value assigned to it.

            Console.WriteLine("Employee ID : {0}", latestEmployee.EmployeeID);


This is another advantage of using an ORM tool like EF. We need not write any additional code to fetch the primary key and assign it to a property on the entity object. The framework takes care of it automatically. For the sake of clarity I create d a small helper method which will output the values of the properties of employee as follows


        private static void DisplayDetails(Employee employee)

        {

            Console.WriteLine("First Name : {0}", employee.FirstName);

            Console.WriteLine("Last Name : {0}", employee.LastName);

            Console.WriteLine("Address : {0}", employee.Address);

            Console.WriteLine("City : {0}", employee.City);

            Console.WriteLine("Date Of Birth : {0}", employee.BirthDate.Value.ToShortDateString());

            Console.WriteLine("Hire Date : {0}", employee.HireDate.Value.ToShortDateString());

        }


In order to make use of this helper function I’ll need to pass an instance of Employee entity to it. To ensure that our entity was saved properly to the database, I’ll query it again and pass it to the helper function as

            int employeeID = latestEmployee.EmployeeID;

 

            //fetch existing entity

            Employee fromDB = context.Employees.Single(employee => employee.EmployeeID == employeeID);

 

            DisplayDetails(fromDB);

If you notice carefully, in the above statements we have used the read feature for reading the details of the entity from database.

I can use the alternate method of adding the employee entity to the context. The ObjectContext itself provides an AddObject method which can be used as


            context.AddObject("Employees", latestEmployee);


In this case we need to provide the Entityset name as the first parameter. This happens to be Employees in our case. There is also another method which is provided by the framework to add entities to the context.

            context.AddToEmployees(latestEmployee);

In this case we make use of the AddToEmployees method to add anew employee entity to the context. All 3 methods described here ultimately have the same effect.

 Note : You might see that if you run the example again and again the same ID might begetting assigned to the new employee. This happens because I am using a file based database. This is set in the connectionstring using AttachDbFilename property. I am not connecting to an instance of SQL server database. Hence when the code is compiled, the database file gets copied to the output folder. You can check this behavior by monitoring the contents of Bin/Debug or Bin/Release folder depending on the type of build you perform.

Perform Update Operation Using Entity Framework 4

Lets use the same entity that we retrieved from the database and perform some updates to it. This is as simple as any DotNet related code. We already know how to get the details into the entity object. We can update the properties to the new values and call the SaveChanges method on the context to reflect the changes back to database.

            int employeeID = latestEmployee.EmployeeID;

 

            //fetch existing entity

            Employee fromDB = context.Employees.Single(employee => employee.EmployeeID == employeeID);

 

            DisplayDetails(fromDB);

 

            //update entity details

            fromDB.City = "Bengaluru";

            fromDB.BirthDate = DateTime.Today.AddYears(-35);

            fromDB.HireDate = DateTime.Today.AddYears(-5);

 

            //update to DB

            context.SaveChanges();


I have modified the City, BirthDate and HireDate for the employee which was fetched from the database and saved back the changes. To verify whether this was correctly saved or not I can request the same details again from the database and display the details to verify the updates as

 

            fromDB = context.Employees.Single(employee => employee.EmployeeID == employeeID);

 

            DisplayDetails(fromDB);


As expected the results show that the fields are indeed updated.

 

Perform Delete Operation Using Entity Framework 4

Delete is similar to add in a sense that we need to pass a reference to an existing entity object that we wish to be deleted from the database. Here is an example.

            context.Employees.DeleteObject(fromDB);

 

            //update to DB

            context.SaveChanges();

I have made use of the DeleteObject method of EntitySet to delete the object.

You can verify that the object was actually deleted from the database or not by using the same query that we used earlier. I leave that as an exercise to the reader.

If you are too lazy to try that out yourself, feel free to uncomment the last couple of lines of the attached code to see how it works. 

The framework provides another alternative to delete objects from the context. This has a similar naming convention to the add method but has different set of parameters.

            context.DeleteObject(fromDB);

Here we are bypassing the entityset (Employees) and calling the DeleteObject method on the ObjectContext directly. Since each object is unique this is able to delete the correct object when we save the changes.

Conclusion



So in this article we saw how to perform CRUD operations using EF 4. [Update 25th Sept 2010] There are alternate ways of adding and deleting entities using a different syntax. I’ll update this post sometime later with those updates as well. But this is the preferred approach so I would suggest you can use this one over the others.


I have updated the post with alternate syntaxes for the adding and deleting the entities from the context. I have also updated the code used for the demo. While adding and deleting the entities, I prefer the syntax which is based on strong type of EntitySets like context.Employees.AddObject(latestEmployee) and context.Employees.DeleteObject(fromDB). This is also the recommended approach.

In these examples I have demonstrated simple object persistence. In a real life scenario it hardly happens to be as simple as this. So I would definitely follow up this post with another one which demonstrates how to persist a complex object graph. Sometimes while writing one posts we generate ideas for the future ones and that is exactly what is happening with this series for me. I’ll finish this post here.

As usual the complete source code is uploaded to dropbox and is available for download here.

Until next time Happy programming :)

Further Reading

Here are some books I recommend related to the topics in this post.

 


8 comments:

  1. Good one Nilesh :)

    ReplyDelete
  2. Awesome Nilesh.. you describe it in a simple yet powerful manner.. i was on middle of my test project related to learning entity framework. done my database on model first approach.. then i was lost.. what is next.. ho do i start manipulating data.. then i found your nice article..it gave me a boost start...

    if i might not miss something in this nice article.. i must like to say all who reading this post.. we must maintain model in a separate class library project. by doing so you can re-use this model anywhere again. and you must add reference to class library project from your application project...so that you can use the classes generated by EF in nice manner...

    thnx in advance

    ReplyDelete
  3. @Charith Thanks for the compliemnts. I agree with you that models should reside in separate assembly. Only then we'll able to reuse them. Also by putting them in separate assembly we can ensure that we have the right encapsulation.

    ReplyDelete
  4. Nice Article Nilesh.You explained it nicely in a correct manner.Your article helps me a lot.

    Thanks a lot :)

    ReplyDelete
    Replies
    1. Thanks for the compliments. Glad to know that it helped you

      Delete
  5. Thank you nilesh. Very informative and good explanation.

    Is it possible for you to add article for validation of entities in EF and also how to manage validation classes. (Example: Either we should maintain a one big class of entity validation or how to logical divided and things of that nature.)

    ReplyDelete
  6. is there any material to perform CRUD in entity framework 6.0 in C# windows forms?

    ReplyDelete
  7. thanks guys, its really helpful

    ReplyDelete