general

ADONET Entity Framework Example

Aug 11, 2011
Ricardo Acevedo

The Entity Framework (EF) is the new component of ADO.NET. The main goal of EF is to provide an ORM that significantly reduces the pain of dealing with data models in a data programming application. Developers can take advantage of Language Integrated Query (LINQ) to raise the programming experience and handling a very database intensive code with an entity model.

Integrating EF into a .Net Solution is easy to do. First, you need to generate a model based on a database structure, then perform a simple operation against the entity model and then see the equivalent operation directly in the database.

First, we need to create a relational database, for this example we’ll use the NorthwindOA database provided in MSSQL Server 2008.

Generating the entity model 

In order to create our entity model, we need to create a Class Library project. For this example, we  created the project using Visual Studio 2010, and then we can generate our model:

 

  1. Right click and select “Add New Item”.
  2. In the left panel, select the “Data” option and then click on “ADO.NET Entity Data Model”.
  3. You can fill in the name of the model; our example is called MyFirstEntityModel.edmx.
  4. Click on the “Add” button.
  5. In the next window, select “Generate from database”; this option will use the provided data base to create our entity model.
  6. Next, we will provide the database connection settings. Choose the tables to be included in the model and fill the model’s name.
  7. Click “Finish” button.

After this, you can see the generated model screen; here you can edit any entity and Explorer view, you can see the new created item called MyFirstEntityModel.edmx. Under this, you have the MyFirstEntityModel.Designer.cs class that contains two main regions: Context and Entities. They  contain partial classes that represents each chosen table of the database.