Saturday, May 30, 2009

.Net 3.5 New feature - Entity Framework

Why something like Entity Framework was needed?
Before the release of .NET 3.5, there was a substantial mismatch between the relation database model and the business entity model. Let’s take an example to understand it in a better way.We want to develop an application for a hospital with the following set of entities.
  • Users: The users who will be logging into the system.
  • Roles: The role of the users.
  • Donors: Some of the users may be donors as well.

I have prepared the following tables which contain information about the Users, Roles and Donors.



Now suppose our business need tells us to display the name and detail of the doctors who are also donors. Then I can think of writing the following query:
Select Users.User_Id, Roles.Role_Name, Users.First_Name, Users.Second_Name, Users.Middle_Name, Users.Last_name from Users INNER JOIN Roles ON User.Role_Id = Roles.Role_Id INNER JOIN Donors on Donors.User_Id=User.User_Id WHERE Role.Role_Name=’Doctor’
I can see two major issues here.

  • We need complex queries (although it’s not that much complex here) with too many joins to populate the business entities.
  • If we have the business entities like Roles, Users, Donors, it will not have any business significance until we populate these with this kind of complex queries.

These issues can be dealt in a better way with the help of Entity Framework.
Prerequisites for using Entity Framework

  • Visual Studio 2008 with SP-1
  • Net Framework 3.5 with SP-1
  • SQL Server 2005

Getting started with Entity Framework
Open your solution in the VS2008, click on add new item and add a new ADO.NET entity model.

Provide the name of the entity data model say "NICRModel" and click on Add.The visual studio shall show the following screen.

Now select "Generate from the database" and click on the Next button.In this screen provide the SQL DB settings.


Clicking on the Next button brings up the following screen where in you can select the tables for which the entity data model has to be created.



Click on finish button.You will be shown the following entity model diagram.


As you can see, the diagram shows the business entities with their respective relations.

Now consider the above scenario , we have to find out the details of the doctors who are also donors.

In that case you will have to create an object of the entity model..
NICREntities NicrEntity = new NICREntities();

Now find out the desired information using LINQ
IQueryable UsersQuery = from p in NicrEntity.Users
where p.Roles.Role_Description == "Doctors" && p.Donor.Count>0
select p;

You can cleary see out from here that the much of our effort is simplified by the Entity Framework concept.