Pages

I've migrated my blog

Thanks for visiting my blog. I am no longer maintaining this and I've migrated the blog to my personal domain . If you would like to follow my blog kindly use my new RSS feed

Friday, April 1, 2011

Entity Framework 4.0 As Class Library - Part 2

As the continuation of my previous blog post, In this blog post we are going to explore on how to consume the data access class library created in the previous blog post.

Consuming the Data Access Library created using Entity Framework 4.0 involves the following two steps.
  1. Adding reference to the class library
  2. Adding the connection string in the config file (App.config or Web.config)

Let us see how can we do these steps using a console application. To keep things simple I have opt for a console application. It holds the same for an ASP.NET , Windows Form, WPF,WCF, etc.

Console Application Creation

Create a new console application called "HrdConsoleApp"



Add a reference to the Class library

Right click on references and refer the class library "HRD.DataAccess" that we have created in the last blog.


Add reference to System.Data.Entity Library



Add the App.Config file to the console application by right clicking on the project name in the solution explorer and select "Add->New Item"




Copy the connection string from the App.Config file created in the HrdDataAccess Class library Project created earlier and paste it in the App.config file created in the previous step.



Thats all now it is all set to access the database with only minimal amount of code.. Here we go!!

Implementation Code:
using System;
using System.Linq;
using HRD.DataAccess;

namespace HrdConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            HRDEntities hrdEntities = new HRDEntities();
            foreach (Employee employee in hrdEntities.Employees.ToList())
            {
                Console.WriteLine("Name: " + employee.Name);
                Console.WriteLine("Department: " + employee.Department.Name);
                Console.WriteLine("########################");
            }
        }
    }
}

Output




Summary:

In this blog series (Part 1 and Part 2) we have seen how to create the data access layer using Entity Framework 4.0 as class library and how to consume it in an application. With the introduction of Entity Framework developing the code for data access layer is no longer a tidy and time consuming job!!

No comments:

Post a Comment