Entity Framework Database First and Code First Simple Knowledge

This post is meant to provide you direct and simple code to test out the ADO.NET Entity Framework in both Database First Approach and Code First Approach, with assumption that you already know what Entity Framework is.
You can refer to mirosoft site for the good definition.

But here is my definition:
Entity Framework is a layer of code provided by Microsoft within .NET Framework to allow you to have an abstraction of your database in form of model objects for you to access your database without having to worry about directly interact with the database.

What is it for?
Mainly it’s for improving the time of market on an application. With it, you surely finish your code faster.

Performance Issue
Surely it’s can’t be as fast as you directly hit the database using Stored Proc. You’ll surely lose some performance when you use LinQ to SQL through Entity Framekwork.

 

- Should we use it or should we not is another debate post.


Let’s jump into how we can actually use it.

Entity Frame Database First Approach Model
1) Create Entity Frame Database First Approach Model
 

- Right click on your project -> Add new item -> Select ADO.NET Entity Data Model -> Name it Model1.edmx

- Follow instruction on the wizard, select the server -> select database -> select tables you want to add to the model

1) By default this will create a model with Entity Container Name as DatabaseName+Entity

- For my case, my database is DiTran, so it’s DiTranEntities

2) Namespace for the model will be DatabaseName + Model

- For my case, it’s DiTranModel


2) Try to retrieve test data:
 

Using the code below.

 

NOTE NOTE: Connection String for entity framework data context is different than regular sqlClient connection string. I’ve created a method to generate Entity Framework connection string as CreateEntityConnectionString().

 

 

 

/*

* Author: Di Tran

* Date: 07-25-2011

* Description: Get test data

*/

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using DiTran.DataManager.Data;

using System.Data.SqlClient;

using System.Data.EntityClient;

using System.Configuration;

namespace DiTran.DataManager

{

public class DiTranDataManager

{

private tblEmployee _employee;

public DiTranDataManager()

{

}

public tblEmployee GetEmployee()

{

string conString = this.CreateEntityConnectionString();

DiTranEntities1 _theEntities = new DiTranEntities1(conString);

this._employee = _theEntities.tblEmployees.FirstOrDefault();

return this._employee;

}

public string CreateEntityConnectionString()

{

// Specify the provider name, server and database.

string providerName = "System.Data.SqlClient";

string serverName = @"ServerName";

string databaseName = "DiTranDatabase";

// Initialize the EntityConnectionStringBuilder.

EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder()

{

Provider = providerName,

ProviderConnectionString = new SqlConnectionStringBuilder()

{

DataSource = serverName,

InitialCatalog = databaseName,

IntegratedSecurity = true

}.ToString()

};

 

// Set the Metadata location.

entityBuilder.Metadata = @"res://*/Data.Model1.csdl|

res://*/Data.Model1.ssdl|

res://*/Data.Model1.msl";

return entityBuilder.ToString();

}

}

}

 

Entity Framework Code First Approach
What about Entity Framework Code First Approach?
There are 2 ways you can go about with Code First Approach?
1) Work with existing Database First Approach Model (.EDMX) file
 

Open the.EDMX file in VS 2010 -> Right Click on the model screen -> Add Code Generation Item -> Select ADO.NET DbContext Generator -> Use default name Model1.tt -> Click Add

Now you’ll get 2 files required for Code First Entity Framework Approach:

1) Model1.Context.tt: This file hold a sub file Model1.Context.cs which is the data context for the entity.

If you look into Model1.Context.cs file, you will see that it derive from DbContext, and not ObjectContext as .EDMX Model from Database First Approach.

2) Model1.tt : this file will hold a lot of model files and each file represent the model for each table within the database that you linked to.


NOTE: So for this case, you already have an Database First Entity Framework model, and you just happen to want to convert it to Code First Entity Framework model. This wizard helps you automatically generate the Code First Models for you using T4 code generation.

2) You manual generate the Code First Approach Entity Framework model from the beginning (Fresh Start).
 

What exactly do we need to use Code First Approach?

We will need 3 things:

1) The DBContext inherited classes such as followed:

This is the Core class that will connection everything together.

What does it do exactly?

1) Bind your model to the database table Using DBSet<>

2) Map the your model to the binding using DBModelBuilder object

3) Connect to database, and allow you to retrieve data from database in dataset of model objects


 

EXAMPLE:

/*

* Author: Di Tran

* Date: 07-11-2011

* Description: The db context

*/

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data.Entity;

using DiTran.Models;

namespace DiTran.DataManager

{

public class DiTranDBContext : DbContext

{

public DiTranDBContext() : base(){}

public DiTranDBContext(string conString)

: base(conString)

{

 

}

protected override void OnModelCreating(DbModelBuilder modelBuilder)

{

modelBuilder.Configurations.Add<Employee>(new DataMap.Map_Employee());

 

base.OnModelCreating(modelBuilder);

}

public DbSet<Employee> Employees{get;set;}

}

}

 


2) Model classes that mimic the database table
 

When I say mimic the database table I mean matching exactly on data type and name:

1) Model Name = Table Name

2) Model Property Name = Table Column Name

What do you do when they don’t match:

- No Problem, that’s why we need the mapper class in number 3


 

EXAMPLE:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace DiTran.Models

{

public class Employee

{

public int EmployeeID { get; set; }

public string EmployeeName { get; set; }

public string EmplyeeTypeName { get; set; }

public string EmplyeeParentID { get; set; }

public Employee EmplyeeParent { get; set; }

 

}

}


3) Mapper class (this is not required but recommended for code cleanness).

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using DiTran.Models;

using System.Data.Entity.ModelConfiguration;

namespace DiTran.DataManager.DataMap

{

class Map_Employee : EntityTypeConfiguration<Employee>

{

public Map_Auditor()

{

//Map table since it's different name

this.ToTable("tblEmployee");

//Map property with different name

this.Property(item => item.EmplyeeTypeName).HasColumnName("EmployeeType");

//Map id to

this.HasOptional(item => item.EmplyeeParent).WithMany().HasForeignKey(childItem => childItem.EmplyeeParentID).WillCascadeOnDelete();

}

}

}


4) Test Class

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using DiTran.DataManager;

using DiTran.Models;

namespace DiTran.DataManager.DataManager

{

public class DBContextDataManager

{

private DiTranDBContext _context;

public DBContextDataManager()

{

this._context = new DiTranDBContext(@"Data Source=DBDiTranServer;Initial Catalog=DiTranDB;Integrated Security=SSPI;");

}

public Auditor GetEmployee()

{

return this._context.Employees.FirstOrDefault();

}

}

}