ASP.NET, Coding

Introduction to Entity Framework 5.0 – Part 1

EF 5.0 is the latest version of Microsoft ADO.NET entity framework which is the Microsoft ORM (Object Relational Mapping) which enables .NET developers to work with relational data using domain-specific objects. It eliminates the need for most of the data access code that developers usually need to write. (Read more here).

Entity framework can be used to in three different models (workflows):

Database First: which you building the database first and you reverse engineer the database to generate the classes (entities) and its mapping (.edmx file in xml format to map all database tables, views, stored procedures and column into classes, methods and properties.

Model First: where you can build your model first (edmx file) based on the business domain adding all the business entities and its logical relation to each other and later you can generate the classes and also the database form that model.

Code First (my favorite): here you can define your domain model using POCO (Plain Old CLR Object) classes, which have no dependency on Entity framework. In this case you need no .edmx file as the mapping will be on the fly using convention over configuration feature in the entity framework.

In this article, I will show you how to use entity framework code first in your application. First, create an ASP.NET MVC web application. And add to the solution two Library projects one will hold the entities (business domain models) and the other will hold the DbContext and its configuration.

EF project Structure

Start at your entities project (named EFCodeFirstDemo.Entities) and start adding your domain model classes. Here I will add two classes:

 public class Person
    {
        public long Id { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public string Birthdate { get; set; }
        public List
Addresses { get; set; } } public class Address { public long Id { get; set; } public string Street { get; set; } public string Country { get; set; } }

Look once you build your desired classes and its logical relations to each other (here every Person have one or more Address). EF code first framework will use any property called Id or property combined the class name with Id as the primary key for that table when it generates the database. If it can’t find that property an exception will be thrown in the runtime saying ‘There is no key. Also the default configuration of classes and properties types for example mapping strings with default length except you specify otherwise.

To build your context, the class mapping the database object so you can query the database or save changes to it, you need to install the entity frame work. You need three DLLs to start using EF:

  • Entityframewok.dll
  • System.Data.dll
  • System.ComponentModel.DataAnnotations.dll

The best way to install entity frame work into your solution is using NuGet package manager.

Install EF using Nuget

Also you need to inherit from DbContext class and adding the entities DbSet to your model.

using System.Data.Entity;
using EFCodeFirstDemo.Entities;
 
namespace EFCodeFirstDemo.DatabaseMapping
{
    public ContactContext(string connectionString):base(connectionString)
    { 
    }	
    public class ContactContext : DbContext
    {	
        public DbSet Persons { get; set; }  
        public DbSet
Addresses { get; set; } } }

To start using the context to query the database and save you changes. Just you need to instantiate the Context in your ASP.NET MVC controller.

public class HomeController : Controller
{
   private string connection = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
   public ActionResult Index()
   {
     var people = new List();
      using (var context = new ContactContext(connection))
      {
            context.Persons.Add(new Person
                           {
                                  FirstName = "Joe",
                                  LastName = "Jack",
                                  BirthDate = DateTime.Now, 
                                  Addresses = new List
{ new Address { Country = "Egypt", Street = "Tahrir st."} }, }); context.SaveChanges(); //get all the people from the database people = context.Persons.ToList(); } return View(people); } }

Once you press run the application, the entity framework will use your code to build the database in your Microsoft SQL Server Express edition (if exists) or you can reconfigure the context to connect to the local SQL Server instance. This can be done by change the connection string in the web.config file.

 
      
 

Once you hit start (F5 key) you will see the database create:

EF contacts Databse

EF database diagram

Note, class person is mapped to table People as entity framework pluralize the table name also addresses table contain property name Person_Id which is a foreign key to table People as the Person class has list of Addresses for that person. You can find the added person data with its related list of addresses with a foreign key constraint:

After the Index action method in the home controller done executon it returns the view Index in the ~/Views/Home/Index.cshtml. we did some changes in that default view as we remove all the text and replace it with this code that accepts a model of type Listand it uses foreach to iterate the model and write the first name in a span.

@model List 
@section featured {
    
@foreach(var p in Model) { @p.FirstName
}
}

EF Index

Note this is the Razor syntax that introduced in ASP.NET MVC 3

If you look at the table created, you will find that entity framework uses the default configuration of all columns in the People table.

  • The Id by default made bigint and not null and primary key.
  • FirstName and LastName by default they are nvarchar(Max) and allow null
  • Birthdate is a datetime and does not allow null.

You can change the default configuration for most of the default values, this can be done using Data Annotation or by fluent APIs. Here we will use data annotation for change the table name, column name, column data type and column null-ability.

public class Person
    {
        [Key]   
        public long NoNamingConventionKey { get; set; }
        [Required]   // does not allow null
        public string FirstName { get; set; }
        [StringLength(100)] // max length of the column 
        public string LastName { get; set; }
        public System.DateTime BirthDate { get; set; }
        public List
Addresses { get; set; } }

So which model should I use?
After you had read this article and know what code first is, the question should I use code first workflow for building the application? It depends, if you not yet started your application it’s easier to build the domain entity classes and then generate the database when you needed. But if you have your database already exists so you can use the database first workflow that will be more convenient.