Showing posts with label Entity Framework. Show all posts
Showing posts with label Entity Framework. Show all posts

Monday, May 19, 2014

Entity Framework : How to generate model using Entity Framework Design

This is a step-by-step walkthrough which will generate the Model using Entity Framework Designer and then generate a database schema from the model. The model is stored in a an EDMX file

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.

1. Create new Application

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

2. Create Model
To create model, I will use Entity Framework Designer
  • 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 Empty Model from Entity Data Model Wizard and then click Finish.

You will see Entity Framework Designer is opened with a blank model, Now you can start adding entities, properties to the model.
  • Right-click on the design surface and select Add New -> Entity…
  • Enter Manager as the entity name and ManagerId as the key name and click OK
  • Right-click on the new entity on the design surface and select Add New -> Scalar Property, enter ManagerName as the name of the property.
  • Repeat the above Step and a new entity Employee with a EmployeeId as a key property.
  • Add EmployeeName ,Designation as a scalar properties to the Employee Entity.
Now we need to add one to many relationship (Association) between them.
  • Right-click on the design surface and select Add New -> Association…
  • Make one end of the relationship point to Manager with a multiplicity of One and the other end point to Employee with a multiplicity of Many.
  • Check Add foreign key properties to 'Employee' Entity and click OK
Now we can generate a database from the model and can use to read and write data.
Now we can generate a database from the model and can use to read and write data.

3. Generating the database
To generate the database
  • Right-click on the design surface and select Generate Database from Model…
  • Click New Connection… and SQL Express (.\SQLEXPRESS)and enter ModelManager as the database name.
  • Select OK and It will be asked if you want to create a new database, select Yes
  • From choose your version, Select Entity Framework 6.0 and click Next
  • Select Next and the Entity Framework Designer will calculate a script to create the database schema
  • Once the script is displayed, click Finish and the script will be added to your project and opened(In my case it is created as ManagingConext.edmx.sql)
  • Right-click on the script and select Execute, you will be prompted to specify the database to connect to, specify .\SQLEXPRESS.

4. Reading and Writing Data
If you checked the Solution Explorer, The Model are already automatically generated based on EDMX file.
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 ManagingContextContainer())
{
// 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  :


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 :


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



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