Code First Approach using Existing Database

Introduction

In this blog we will see how to access existing sql server database with entity framework code first approach.

Step 1: Create console application

Choose code first from database

Program.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace CFAUsingExsistingDB  
  8. {  
  9.     class Program  
  10.     {  
  11.         static void Main(string[] args)  
  12.         {  
  13.             EmployeeContext objEmpContext = new EmployeeContext();  
  14.   
  15.             foreach (var r in objEmpContext.Employees)  
  16.             {  
  17.                 Console.WriteLine("FirstName: " + r.FirstName + " and " + "LastName: " + r.LastName);  
  18.             }  
  19.   
  20.             Console.ReadKey();  
  21.         }  
  22.     }  
  23. }

Output of the application looks like this

Summary

In this blog we have seen how we can access existing sql server database with entity framework code first approach. Happy coding.