Saturday, August 4, 2012

C# Entity Framework in Visual Studio 2010

Some time ago I published an article about LINQ to SQL Classes Generation in Visual Studio 2010. Today I'll show how to use a newer version of Microsoft ADO.NET technology called Entity Framework.
ADO.NET Entity Framework enables developers to work directly with object model of a database instead of writing SQL queries. Developers which  already worked with LINQ to SQL will easily switch to Entity Framework, because the overall using of it is pretty similar.

Ok, let's move on to the example. I created a WPF project with a datagrid in the main window and a simple local database with one single table Employees. Now I want to use ADO.NET Entity Framework to fetch data from the database and show it in my datagrid. Final result will look like this:

C# WPF Datagrid with ADO.NET Entity Framework

In order to add Entity Framework to your application mouse right click on the project then "Add New Item", choose ADO.NET Entity Data Model:

Add New Item ADO.NET Entity Data Model

Then Entity Data Model Wizard will appear, choose "Generate from database":

ADO.NET Data Model Wizard - Generate from database

Click "Next", then choose your data connection. In my case this is my local DB.sdf:

ADO.NET Data Model Wizard - Choose your data connection

Click "Next", then choose desired tables or/and stored procedures. In my case I choose my Employee table, click "Finish":

ADO.NET Entity Framework - Choose your database objects

That's all! You now have Entity Framework Model. Here how you use it in the code:
public List<Employee> GetData
        using (DBEntities context = new DBEntities())
            var query = from e in context.Employees
                        select e;
            return query.ToList<Employee>();
Download the source code of this example (Visual Studio 2010 project).

No comments:

Post a Comment