Create Database Table Using Entity Framework Code First

Introduction

Entity Framework is an Object /Relational Mapping (ORM) framework. It is an enhancement of ADO.NET to work with databases.

Using Entity Framework developers write their query in LINQ and get the result as a strongly typed object.

Description

 Entity Framework can be used in three different ways, which is also called the EF approach:

  • Entity Framework Code First
  • Entity Framework Model First
  • Entity Framework Data First

All the three approaches are used depending on the requirement.

Here, I have explained the very first “Code First.”  Others will be explained in subsequent articles.

Entity Framework Code First

As explained above, in Entity Framework we facilitate work on strongly typed objects.

Step 1: Primarily add new Project/website in Visual Studio and create User Defined type/class.

class

Step 2: Add some properties which will be the columns in Table,

  1. namespace EntityFrameworkCodeFirst  
  2. {  
  3.     public class Employee  
  4.     {  
  5.         public int ID   
  6.       {  
  7.             get;  
  8.             set;  
  9.         }  
  10.         public string EmployeeName  
  11.         {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public decimal Salary  
  16.         {  
  17.             get;  
  18.             set;  
  19.         }  
  20.     }  
  21. }  
Step 3: 

Now add another class which inherits the Data Context class. Data Context class has the responsibility to create databases and maintain connection.

Import: System.Linq;

namespace

Step 4: In Web.config, add connection string,
  1. <connectionStrings>  
  2.     <add name="MyCon" connectionString="Data Source=.;Initial Catalog=MyDatabase;Integrated Security=true" providerName="System.Data.SqlClient" />  
  3. </connectionStrings>  
Step 5: Finally create an instance of EmployeeDataContext class,
  1. protected void Application_Start(object sender, EventArgs e)  
  2. {  
  3.     EmployeeDataContext Edc = new EmployeeDataContext();  
  4.     Employee emp = new Employee()  
  5.     {  
  6.         EmployeeName = "test Name"  
  7.     };  
  8.     Edc.Employees.Add(emp);  
  9.     Edc.SaveChanges();  
  10. }  
Here is the Solution Explorer:

explorer
Table has been created:

table

Hope you like this article, we will get to know about Data Annotations in further articles.
 
Read more articles on Entity Framework:

 

 

Up Next
    Ebook Download
    View all
    Learn
    View all