Code First Approach With Stored Procedure

Introduction

In this article we will see how to access a SQL Server database with the Entity Framework Code First approach and later we will see how to create a procedure using the Fluent API.

Step 1: Create console application

Migrations

Employee.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.ComponentModel.DataAnnotations.Schema;  
  5. using System.Linq;  
  6. using System.Text;  
  7. using System.Threading.Tasks;  
  8.   
  9. namespace CodeFirstApproach_SPApp  
  10. {  
  11.    public class Employee  
  12.    {  
  13.        public Employee()  
  14.        {  
  15.        }  
  16.   
  17.        [Key]  
  18.        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
  19.        public int Id { getset; }  
  20.        public string FirstName { getset; }  
  21.        public string LastName { getset; }  
  22.   
  23.     }  
  24. }

Employeecontext.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data.Entity;  
  4. using System.Linq;  
  5. using System.Text;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace CodeFirstApproach_SPApp  
  9. {  
  10.     public class EmployeeContext : DbContext  
  11.     {  
  12.         public EmployeeContext()  
  13.             : base("EmployeeConn")  
  14.         {  
  15.             Database.SetInitializer<EmployeeContext>(new CreateDatabaseIfNotExists<EmployeeContext>());  
  16.         }  
  17.   
  18.         public DbSet<Employee> Employees { getset; }  
  19.   
  20.         protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  21.         {  
  22.   
  23.             modelBuilder.Entity<Employee>()  
  24.                 .MapToStoredProcedures();  
  25.         }  
  26.     }  
  27. }

Web.config

  1. <connectionStrings>  
  2.     <add name="EmployeeConn"  
  3.     connectionString="Data Source=WIN-B4KJ8JI75VF;Initial Catalog=EmployeeDB;Integrated Security=true"  
  4.     providerName="System.Data.SqlClient"/>  
  5.   </connectionStrings>

The output of the application looks as in this:

Summary

In this article we saw how to access a SQL Server database with the Entity Framework Code First approach and how to create a procedure using the Fluent API. Happy coding.

Up Next
    Ebook Download
    View all
    Learn
    View all
    MVC Corporation is consulting and IT services based company.