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