Friday, February 5, 2010

Basic of Entity Framework


Microsoft has evolved new technology “Entity Framework” to work with Database. Before this, Microsoft has introduced LINQ to work with the objects which derived from the IEnumerable.

Entity framework is easy to use for developer to generate entity classes for tables/views. Entity framework also generates methods to execute stored procedure which you have created into database.

Entity Framework needs Visual Studio 2008 Service Pack2 installed on the machine.

Developer can easily drag and drop the entity object from server explorer to Entity Framework UI. You can easily generate Entity Framework classes from the existing database. Reverse engineering is not possible in Visual Studio 2008. We can expect this functionality from Visual Studio 2010.

Let’s start with Entity Framework

I have used following database structure to understand Entity framework in .Net application.

Table NameContact
Field NameData TypeConstraint
ContactIDIntPK, Auto Increment
FirstNameVarchar(100)Not Null
LastNameVarchar(100)Not Null
TitleVarchar(50)Not Null
AddDateDateTimeNot Null, Default Value = GetDate()
ModifiedDateDateTimeNot Null, Default Value = GetDate()
Table NameAddress
Field NameData TypeConstraint
AddressIDIntPK, Auto Increment

Here we took example of Contact and Address table. One contact person has many addresses like permanent address, office address, Farm-house address etc… So we took “ContactID” field as a foreign key in Address table.

Now let’s create Entity Framework project in .Net IDE.

First open Visual Studio 2008 and select File -> New -> Project option. It will open “New Project” dialog box. Select Project Type “Visual C#” -> “Windows”. Select “Windows Form Application” from Template options. Provide project name, project location and solution name as you want.

Note: You can also take console application or another type of project. But for demo purpose I have chosen windows form application.

After successfully loading project, Right click on project in solution explorer and add new item. In New Item Dialog box select “ADO.Net Entity Data Model” and give name ContactDataModel.edmx. Click on Add button. It will start Entity Framework wizard.
  • In entity framework wizard home page you will get two options “Generate from database” and “Entity model”. You can generate Entity Model using existing database or can use blank entity model to generate your classes manually. [Reverse engineering is not possible in Visual Studio 2008]. Select “Generate from Database” option and click next button
  • In next screen, it allows to create new connection or use existing connection which created before. You can create new connection using “New connection” option. After selecting the proper data connection, Connection string text box will display the connection string used to communicate with the database. You can save the connection string in App.config file. To save connection string in App.Config file just give proper name to “Save entity connection settings in App.config As” textbox. Give “TestEntityEntities” name as connection string name. Click on Next button.
  • In Next screen, you have option to choose which object you want to include in entity framework. You can select Tables, Views and Stored Procedures. Select Address and Contact Table. Click on Finish Button.
  • Entity Framework Wizard will create Entity Framework Model file in your project and option UI in Visual studio. You can see Contact and Address entities.

Entity Framework also generates classes in code behind file for Contact and Address entities. It will generate three classes:
  • Address: This class contains private variables and public properties for each field.
  • Contact: This class contains private variables and public properties for each field.
  • TestEntityEntities: This class is derived from ObjectContext class and has property for Address and Contact entities. This class has method to add new objects in Contact and Address classes.

Now let’s use it in our windows application:

Create new windows form in our windows form application and drag DataGridView control on windows form. Write following code to display all contact information in data grid view.

TestEntityEntities entities = new TestEntityEntities();
var query = from c in entities.Contact select c;
dataGridView1.DataSource = query;

In above code, we created object of the TestEntityEntities class which is generated by Entity Framework wizard in code-behind file. Just use LINQ syntax to get all the contact information from the TestEntityEntities object and display all the contact information in DataGridView object.

Add new record using Entity Framework:

Let go with the Contact Entity. The below code is useful to add new record in contact entity.

TestEntityEntities testEntityEntities = new TestEntityEntities();
Contact contact = new Contact();
contact.FirstName = "test1";
contact.LastName = "test2";
contact.Title = "Mr.";

First of all we create object of Entities class which is created by Entity Framework. Then after we create object of Contact and assign value to the required properties. After successfully assign value to contact entity, we will call “AddToContact” method of TestEntityEntities class. This method will store the data in Contact table but still the data is not committed. So commit the added data, we need to call “SaveChanges” method of TestEntityEntities class.

Edit existing record using Entity Framework:

To edit any existing record, we need to fetch that record and update it in memory and call SaveChanges method to save the changes. Below code is used to edit existing record.

TestEntityEntities testEntityEntities = new TestEntityEntities();
Contact contact = testEntityEntities.Contact.First(c => c.FirstName == "test1");
contact.FirstName = "test1_Changed";

First we create object of TestEntityEntities class. Then after we get contact entity record using TestEntityEntities class method. After getting the record, we just need to update the property values and call SaveChanges function.

Deleting existing record:

To delete the record, we need to load the record and delete it using Entity Framework. Below code is used to delete the record.

TestEntityEntities testEntityEntities = new TestEntityEntities();
Contact contact = testEntityEntities.Contact.First(c => c.FirstName == "test1");

We just load the record and then call DeleteObject method. This method will not commit your changes to database. To commit the changes, we need to call SaveChanges method.

For more information on how to map stored procedure with Entity, click here.


  1. Nice Article ... It would be a very helpful for the beginners..

    I appropriates it.


  2. Nice one, i just learnt how to update the model

  3. How Entity framework know to update primary key? In my case, primary key is not getting updated. Is this has to defined as "Auto Increament" when the table gets created or Entity framework automatically updates the primry key. Currently my application provides PK violation error since it doesn't know how to insert another entry in dB even though I am supplying all the columns except for PK column

  4. You wrote: "You can create new connection using “New connection” option. After selecting the proper data connection, Connection string text box will display the connection string used to communicate with the database.", I would know how can I create a connection with a remote database. In my connection string, by default it has "Data Source=.\SQLEXPRESS" which is the local address of my server and I would change it and put in the connection string the IP address of the remote server and create a connection with it! The remote server isn't my local server!!! can I do it? Thank you!


DotNet Code Guru