Friday, September 19, 2008

Starting with Entity Framework and LINQ

 

So, here I am starting to try out LINQ and Entity Framework. I have been using Hibernate for the past two years can say that there has been many hurdles throughout the learning process of this process of this open source ORM tool. However, Hibernate was a first glance at the power of modern ORMS. I expect the same robustness from LINQ.

After about a week of research (1 hour daily :P) and some patches (download and installation) relevant to VS 2008, .Net Framework 3.5, ADO .NET Entity Framework, I finally managed to have a proper platform to start with LINQ. My aim is to use something similar to Hibernate in C#.

I first created my tables (models) in SQL Server 2005 Express and added some values to it.

imageimage 

 

A console application was sufficient to demo Entity Framework. Note that in order to have Entity Framework Tools in VS 2008, I had to download a few stuffs including patches. Instructions can be found at http://oakleafblog.blogspot.com/2007/12/entity-framework-beta-3-available-for.html.

In my VS2008 console Application, I added an ADO.NET Entity Data Model named EntityFrameworkDemoModel.edmx. A wizard was presented to me and I chose to Generate my models from Database. The next screen allowed me to choose my Datasource and store my Connection String in my App.config

 

image

 

In the next screen, I chose the models I wanted to generate:

image

When finished, the following was presented to me :

image

The models was automatically generated in a class. As opposed to hibernate, all models were regrouped in one single class. Now to test, whether using LINQ, I could obtain all data in my tables through my Business Objects which have been generated, I ran the code below:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Objects;
using System.Text;

namespace EntityFrameworkDemoApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("ADO .NET Entity Framework Demo");

            DemoDBEntities demoDb = new DemoDBEntities();
            ObjectQuery<UserRole> userRoleQuery = demoDb.CreateQuery<UserRole>("SELECT VALUE u FROM UserRole as u");

            foreach (UserRole userRole in userRoleQuery.Execute(MergeOption.NoTracking))
            {
                Console.WriteLine("User Role is " + userRole.UserRoleName);
            }
            Console.ReadLine();
        }
    }
}

 

And my result is as follows:

image 

 

I must say, its not bad at all for now. My next step will attempt building (if it does not exist already) a generic class that will handle CRUD operations for all class.

No comments: