Saturday, December 19, 2015

Entity Framework Code First Approach

Code First approach does not actually Mean that you can not utilize existing database. Instead, it lets you deal with existing database or you can start with code and Entity Framework will create new database. Let us See both approaches,

Existing Database

Open your project in Visual Studio 2013 and click Add New Item -> ADO.NET Entity Model
Click on the Code First from database option. This wizard will lead you to create model classes.



Once model classes are created, Now the Existing and new database options for "Code First" approach become similar and you can apply migrations (from code to database) after you change anything in the model classes in code. Following approach is the same for both options of "Code First" Approach

New Database

Create Model Classes

Note: For Existing Database Option, this step is not required because wizard already creates classes.

First add Entity Framework Nuget Package if not installed already. Add new File and include following namespaces,
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;

Let us include Parent Child Tables classes

public class ParentTable
   {
       [Key]
       public int ID { getset; }
       public string Name { getset; }
 
       public virtual List<ChildTable> ChildTables { getset; }
   }
 
   public class ChildTable
   {
       public int ID { getset; }
       public string Title { getset; }
     
 
       public int ParentID { getset; }
       public virtual ParentTable ParentTable { getset; }
   }
 
 
   public class MyDBContext : DbContext
   {
       public MyDBContext()
           : base("FirstDB")
       { }
       public DbSet<ParentTable> ParentTables { getset; }
       public DbSet<ChildTable> ChildTables { getset; }
 
   }

Note in the above code, Entity Framework will search "FirstDB" as connection string in the configuration file and if it is not there then it looks for the local database. See how parent child relation is created in both classes. 

Add connection string in the Web.config under "Configuration" section
<connectionStrings
  <add name="FirstDB"  
        providerName="System.Data.SqlClient"  
        connectionString="Server=.\;Database=FirstDB;Integrated Security=True;"/> 
</connectionStrings>

If you do not provide the connection string, visual studio will use the default (local database) from here (you can change the value),



Above is the connection string for default instance of SQL express. if there are more than one SQL Express instances, you can name for other instances. like i have following instances running in my machine services,



You can test the connection from visual studio Server Explorer -> Add connection,


Enable Migration

For making a migration connection between database and model classes, first step is to enable migration.This command will create migration folder (under your project) and under this folder Configuration.cs file is created (Seed function in this class is used to pre-populate database tables.

For normal enabling migrations, following is command
Enable-Migrations
Note in some cases it throws error "No context type was found in the assembly". so following command can be used. it throws error because the default startup project is different than the project where migration is required.

it means that cc.web is startup project and actual migration is required at cc.dataaccess project.
Enable-Migrations -ProjectName CC.DataAccess -StartUpProjectName CC.Web

Following command can be used to specify particular data context for which migration is needed,
This scenario comes when we have multiple data contexts like identity or other data contexts.
Enable-Migrations -ContextTypeName mydatacontext

Add Migration

The simple command is,
Add-Migration MigrationName

Entity Framework will create some classes with "MigrationName" name.

You can also include ContextTypeName and ProjectName information as we did in the Enable Migration step for more accurate results.

Update Database

This is the step where actual database changes are applied from classes to Database.The simplest command is,

Update-Database

Following is how tables and their relationships are created,



Errors and Issues for Local DB

  1. First issue i faced was like "Directory lookup for the file failed with the operating system error 2(The system cannot find the file specified.). CREATE DATABASE failed", The resolution of this issue was to include "App_Data" (ASP.NET Folder) folder in the project ( in case you are using local db, For express or normal versions of SQL Server, it is not required). 
  2. The other issue was like, "The database MDF cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported." which means that you have installed multiple instances of SQL Server. The database file was created by latest version and your visual studio is accessing through older version. I by passed this issue by using SQL Express and there was no issue faced. 

No comments:

Post a Comment