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
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirstApproach_SPApp
{
public class Employee
{
public Employee()
{
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}Employeecontext.cs
sing System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirstApproach_SPApp
{
public class EmployeeContext : DbContext
{
public EmployeeContext()
: base("EmployeeConn")
{
Database.SetInitializer<EmployeeContext>(new CreateDatabaseIfNotExists<EmployeeContext>());
}
public DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>()
.MapToStoredProcedures();
}
}
}Web.config
<connectionStrings>
<add name="EmployeeConn"
connectionString="Data Source=WIN-B4KJ8JI75VF;Initial Catalog=EmployeeDB;Integrated Security=true"
providerName="System.Data.SqlClient"/>
</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.


Mohsin AzamPosted Jul 17, 2017, 2:50 AM EDT
Not complete article
Rudra SinghPosted Mar 15, 2017, 4:31 AM EDT
My database is located in local db
Rudra SinghPosted Mar 15, 2017, 4:25 AM EDT
When I give connection strings then it show error.
Ravi PatelPosted Sep 14, 2015, 4:47 AM EDT
good article but how can i use select stored procedure in code first approach ?
Pankaj Kumar ChoudharyTOP 100Posted Aug 30, 2015, 8:48 PM EDT
Nice Explain Sir..........
Abdul Momin Tasleem AnsariPosted Jun 11, 2015, 2:14 AM EDT
NIce Article
Rahul Kumar SaxenaTOP 100Posted May 12, 2015, 7:41 PM EDT
Good Show...
Santhakumar MunuswamyPosted May 12, 2015, 11:16 AM EDT
Good