Introduction

In this article we will see how to access a SQL Server database with the Entity Framework Code First Approach using data 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. namespace CodeFirstApproach_SPApp
  9. {
  10. public class Employee
  11. {
  12. public Employee()
  13. {
  14. }
  15. [Key]
  16. [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  17. public int Id { get; set; }
  18. public string FirstName { get; set; }
  19. public string LastName { get; set; }
  20. }
  21. }

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. namespace CodeFirstApproach_SPApp
  8. {
  9. public class EmployeeContext : DbContext
  10. {
  11. public EmployeeContext()
  12. : base("EmployeeConn")
  13. {
  14. Database.SetInitializer<EmployeeContext>(new CreateDatabaseIfNotExists<EmployeeContext>());
  15. }
  16. public DbSet<Employee> Employees { get; set; }
  17. protected override void OnModelCreating(DbModelBuilder modelBuilder)
  18. {
  19. modelBuilder.Entity<Employee>()
  20. .MapToStoredProcedures();
  21. }
  22. }
  23. }

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>

Program.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace CodeFirstApproach_SPApp
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. EmployeeContext empContext = new EmployeeContext();
  13. Employee emp = new Employee()
  14. {
  15. FirstName = "Haney",
  16. LastName = "Jow"
  17. };
  18. empContext.Employees.Add(emp);
  19. empContext.SaveChanges();
  20. Console.WriteLine("Inserted");
  21. Console.ReadKey();
  22. }
  23. }
  24. }

The following shows the output of the application:

SQL profiler

Summary

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