Friday, May 16, 2014

Entity Framework : How to create database using code

This is a step-by-step walkthrough which will create a new database using C# code. We will create one console Application which will create an empty database and will also add new tables too.

Pre-Requisities

We need to have Visual Studio 2013 installed to complete this walkthrough.(You can use older version too like 2010 or 2012 to complete this tutorial.)
Apart from that, You will also need to have NuGet installed on your Visual Studio.

Steps :
1. Create new Application
  • Open Visual Studio, Click File -> New -> Project
  • Click Console Application under templates -> Visual C# -> Windows
  • Enter Name as CreateNewDatabase and Select OK

2. Create the Model

Now we will create two simple model(Employee, Manager) using classes. As a part of demo I'll define both in Program.cs but in a real word application we should define in two separate file/classes.

Add the following two classes in Program.cs.


public class Manager
{
public int ManagerId { get; set; }
public int ManagerName { get; set; }
public virtual List<Employee> Employees { get; set; }
}


public class Employee
{
public int EmployeeId { get; set; }
public String EmployeeName { get;set; }
public String EmployeeDesignation { get; set; }
public int ManagerId {get;set;}
public virtual Manager Manager { get; set; }
}


If you have notice I have made the two navigation properties (Manager.Employee and Employee.Manager) virtual. This enables the Lazy Loading feature of Entity Framework. Lazy Loading means that the contents of these properties will be automatically loaded from the database when you try to access them.

3. Create a Context

Before creating a context, first we will install the EntityFramework Nuget package.
  • Click Project -> Manage NuGet Packacges
  • Select the online tab and then select the EntityFramework Package and Install.
Now we need to create a session so that we can query and save data into the database, we need to define a derived context (System.Data.Entity.DbContext) and exposes a typed DbSet<Entity> for each class in our model.

Add following derived context in the the Program.cs file.
public class ManagingContext : DbContext
{
public DbSet<Manager> Blogs { get; set; }
public DbSet<Employee> Posts { get; set; }
}

Program.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;

namespace CreateNewDatabase
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }

    public class Manager
    {
        public int ManagerId { get; set; }
        public String ManagerName { get; set; }
        public String ManagerAddress { get; set; }
        public virtual List<Employee> Employees { get; set; }
    }

    public class Employee
    {
        public int EmployeeId { get; set; }
        public String EmployeeName { get;set; }
        public String EmployeeDesignation { get; set; }
        public int ManagerId {get;set;}
        public virtual Manager Manager { get; set; }
    }

    public class ManagingContext : DbContext
    {
        public DbSet<Manager> Managers { get; set; }
        public DbSet<Employee> Employees { get; set; }
    }
}

4. Reading and Writing Data

Now its the time to implement the Main method in Program.cs. It will create a new instance of our context and then uses it to insert a new Manager. I have used LINQ query to retrieve all Manager entry from the database.

class Program
{
static void Main(string[] args)
{
using (var db = new ManagingContext())
{
// Create and save a new Manager entry
Console.Write("Enter a name for a new Manager: ");
var name = Console.ReadLine();

var manager = new Manager { ManagerName = name };
db.Managers.Add(manager);
db.SaveChanges();

// Display all Managers from the database
var query = from b in db.Managers
orderby b.ManagerName
select b;

Console.WriteLine("All Managers in the database:");
foreach (var item in query)
{
Console.WriteLine(item.ManagerName);
}

Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}

Now Run the Application :



5. Where is your Data ??
DbContext has created a database for you. You need to check it into your SQL Express instance or If you have installed it then it will be in your LocalDb. (Both are installed by default with Visual Studio 2013). Click here if you don't know how to connect to database.
The database is named after the fully qualified name of the derived context, In our case that is CreateNewDatabase.ManagingContext



What is NuGet and how to install it on Visual Studio 2013

NuGet is the package manager for the Microsoft development platform including .NET. The NuGet client tools provide the ability to produce and consume packages. The NuGet Gallery is the central package repository used by all package authors and consumers.

How to install NuGet using Visual Studio Extension Manager :
  • Open Visual Studio, Click Tools and then Extension Manager.
  • Navigate to Online, Find NuGet Manager Extension and click Download
  • In the Installer dialog box, click Install.
  • When installation is complete, close and re-open Visual Studio.

NuGet is now ready to use.

What is Entity Framework ?

Entity framework is an Object/Relational Mapping (O/RM) framework. It is an enhancement to ADO.NET that gives developers an automated mechanism for accessing & storing the data in the database and working with the results in addition to DataReader and DataSet. It eliminates the need for most of the data-access code that developers usually need to write.

It allows you to create a model by writing code or using boxes and lines in the EF Designer. Both of these approaches can be used to target an existing database or create a new database. It also provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals.

Following figure shows the overall architecture of the Entity Framework (Source : http://www.codeproject.com/)





Application : Application which is going to use Entity Framework.

EDM (Entity Data Model): EDM consist three main parts- Conceptual model, Mapping and Storage model.
  • Conceptual Model: Defines model classes and their relationships.
  • Storage Model: It is your database design model which includes tables, views, stored procedures and their relationships and keys.
  • Mapping: Mapping consist information about how your conceptual model is mapped to storage model.
ADO.Net Provider: This layer communicates with database using standard ADO.Net.

Data Store : Type of database that you are going to use.

Below are the few Step-by-Step tutorials which will give you the better understanding of Entity Framework :



How TOPT Works: Generating OTPs Without Internet Connection

Introduction Have you ever wondered how authentication apps like RSA Authenticator generate One-Time Passwords (OTPs) without requiring an i...