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
Showing posts with label Data Access. Show all posts
Showing posts with label Data Access. Show all posts

Thursday, August 4, 2011

EF Code First 4.1 in Console Application

Whenever I learn any new things in .Net or experimenting with something, I always prefer to use Console Applications. I personally feel it helps me to concentrate more on what actually I am trying to learn or experiment without any sort of distractions. Moreover it keeps things simple.
            I would like to do the same while learning EF Code First 4.1. Though most of articles in web explain EF with respect to ASP.NET MVC, I favor learning it through my own way using console application without creating any controllers and views!!
Following are the prerequisites to work with EF Code First 4.1.
·         Visual Studio 2010 SP1
·         Entity Framework 4.1
·         SQL CE or SQL Express (SQL CE would be an ideal option for learning purpose)
Let’s go and create the console application.
After creating a console application project, the initial step would be adding references to the following assemblies.
·         EntityFramework (Version 4.1)
·         System.Data.Entity
·      System.ComponentModel.DataAnnotations

Now it’s time to defining the model and the data context. To keep it simple, I am going to define only one model “User”.

 The data context would be as following.



This basic infrastructure is sufficient to run the console application. However as we are using the data context for learning purpose, we might change the model often and doing so will make it inconsistent with the database created automatically when you run the application for the first time. We can circumvent this situation by creating new Data Context initialize class that inherits from DropCreateDatabaseIfModelChanges<TContext> where TContext is the data context that you want to sync with the database always. This class also offers an override function “Seed” using which we can fill the database with some initial data.
The finished code of DataContext initialize class will be like the following.

This datacontext initialize class would create the database whenever the database model changes and create two users by default. Now it’s time to code our Main method, which is actually to trigger all the actions!.
Here we go. Pay close attention to the first statement in the Main method that initializes the database with an instance of DataContextInit class that we have created.
           
Now you can run the application without any configurations. The default behavior of EF Code First will create the database with the same name as your data context name here “MyDataContext” in the SQL Express server installed in the local machine. If you wish to change this default behavior and wanted to use SQL CE instead of SQL Express just add an App.Config to the project and create a connection string with the name of your data context as follows.

That’s it. “Ctrl+F5” and here is the output

Summary
            In this blog post we have explore the basic foundation on how to work with EF CodeFirst using console application. If you want to get your dirty with EF Code First without any distraction Console Application is a better one. You can download the sample code used in this blog post from here.

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!!

Friday, March 25, 2011

Entity Framework 4.0 - Class library - Part 1

In this blog post we are going to explore how to create the data access layer as a
class library using Entity Framework 4.0. By defining the data access layer as
class library, you can reuse it across many applications just by adding a
reference to the class library. In my next blog post, we'll explore how to consume
the library in an application



Entity Framework 4.0 enables the developer to
concentrate on the business logic and business objects without bothering how it
has been manipulated at the database level. You can find a very good tutorial on
Entity Framework
here
to get started.



This blog post uses a sample database named "HRD" which has two tables, Employee and Department.


Step 1: Create a Class Library



Create a new class library project with the name "HRD.DataAccess" and click "Ok"



After creating a new project delete the "Class1.cs" which is created by default.


Step 2: Create the Entity class using the entity framework



Right click on the project name "HRD.DataAccess" and select "Add -> New item".
Select "Data" under installed templates and then select "ADO.NET Data Entity Model".
Type the name as "HrdModel.edmx" and click "Add"




In the Entity Data Model Wizard select "Generate from database" and click "Next"




In the next step select the database name "PCName\sqlexpress.HRD.dbo" and select "Next"




In the next step select the tables names "Department" & "Employee" and click "Finish"



Now we have created the entity model which represent the Object/Relation mapping


Step 3: Building the class library




  1. Select "Build->Configuration Manager"
  2. Change the Configuration of the Project "HRD.DataAccess" to "Release". By default it is "Debug"
  3. Click "Close"
  4. Select "Build->Build HRD.DataAccess"

Thats it!!. Now we have the DataAccess Library ready!! We can reuse it across different .Net Applications

Summary



In this blog we have explored the way of creating the DataAccess class library using entity framework.
in my next blog, we'd explore on how to consume the data access library in an application.

Tuesday, March 15, 2011

SQL CE


Deploying a database in the production server is always a tidy task for the developer.
Installation issues, security issues, migration from development to production
the list goes… This scenario holds good only for network based database. To
avoid this overhead (Headache too!!) some developers may opt for MS Access. This
Access based solution will not work for you if you are going to develop large
database centric application.



You may ask, I am going to leverage only minimal use of database in my
application, so what’s wrong in using access? Good Catch!! You can use access,
so that you can carry your database wherever you are deploying the application.
Hold on, by doing so you are losing a magic. Yes magic! The name of the magic is
Entity Framework. Using Entity Framework you can speak to your database with few
lines of coding and create application in minutes (even in seconds). Sounds
interesting! Do google "Entity Framework"!!.



Fine,Thinking about the solution ?? The answer is SQL CE.


SQL CE is a free, embedded, database engine that enables easy database storage.It does not require you to install a database server in order to use it. You can carry the database in the same way as you did for access by simply copying the SQL CE binaries to the \bin directory of your application.



Advantages of SQL CE

  • No installation/security issues.
  • Works with existing Data APIs - ADO.NET,Entity Framework, etc.,
  • Suitable for light production scenarios
  • No License restrictions. Absolutely Free :-)
  • Can be migrated to SQL Server, SQL Express or SQL Azure easily

You can download SQL CE from here.