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 three approaches are used depending on the requirement.

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 a new Project/website in Visual Studio and create a User-defined type/class.

class

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

namespace EntityFrameworkCodeFirst
{
    public class Employee
    {
        public int ID { get; set; }
        public string EmployeeName { get; set; }
        public decimal Salary { get; set; }
    }
}

 

Step 3. Now add another class that inherits the Data Context class. The data Context class has the responsibility to create databases and maintain connections.

Import: System.Linq;

namespace

Step 4. In Web.config, add the connection string,

<connectionStrings>
    <add name="MyCon"
         connectionString="DataSource=.;InitialCatalog=MyDatabase;IntegratedSecurity=true"
         providerName="System.Data.SqlClient"/>
</connectionStrings>

Step 5. Finally, create an instance of EmployeeDataContext class

protected void Application_Start(object sender, EventArgs e)
{
    using (EmployeeDataContext Edc = new EmployeeDataContext())
    {
        Employee emp = new Employee()
        {
            EmployeeName = "testName"
        };
        
        Edc.Employees.Add(emp);
        Edc.SaveChanges();
    }
}

Here is the Solution Explorer has been created.

explorer table

Conclusion

Hope you like this article. We will get to know about Data Annotations in further articles.

Read more articles on Entity Framework


Similar Articles