Monday, May 19, 2014

Entity Framework : How to create code using Existing Database

This is a step-by-step walkthrough which will use existing database to create the model. We will create one console Application which will generate the model using existing databases.

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 and the 6.1 or later of the Entity Framework Tools.

1. Connect to an Existing Database

Check here to see how can you connect to existing database. I have already created one database in my previous blog. I ll use the same database(CreateNewDatabase.ManagingContext) to generate the model.

2. Create the Application

  • Open Visual Studio, Click File New Project
  • Click Console Application under templates Visual C# Windows
  • Enter Name as CreateModelUsingExistingDatabase and Select OK

3. Reverse Engineering Model

Here I am going to make use of the Entity Framework Tools for Visual Studio to help us generate some initial code to map to the database.
  • In Solution Explorer, Right Click on your Project and then Add New Item...
  • Select Data from the left menu and then ADO.NET Entity Data Model
  • Enter Name as Managing Context and click OK
  • Now Select Code First From Database from Entity Data Model Wizard and then click Next.


  • Select the connection to the database you created and set Entities name too and click Next.
  • From choose your version, Select Entity Framework 6.0 and click Next.
  • Click the check box next to Tables to import all tables and click Finish


Once you are completed, you will see a number of items that have been added to the project.

App.Config : This file contains the connection string to the existing database.

<connectionStrings>
<add name="ManagingContext" connectionString="metadata=res://*/ManagingContext.csdl|res://*/ManagingContext.ssdl|res://*/ManagingContext.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=MYNA\SQLEXPRESS;initial catalog=CreateNewDatabase.ManagingContext;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
</connectionStrings>

ManagingContext : A ManagingContext class has been added to your project. This represents a session with the database, allowing us to query and save data. In the default constructor there is name=ManagingContext. This tells Application that the connection string to use for this context should be loaded from the configuration file.

public partial class ManagingContext : DbContext
{
public ManagingContext()
: base("name=ManagingContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Manager> Managers { get; set; }
}

Model classes :
You will also observer Manger and Employee class are also added to the project. These are the domain classes of the Application


4. Reading & 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 Blog
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 Blogs 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 :


1 comment:

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