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.
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 which inherits the Data Context class. Data Context class has the responsibility to create databases and maintain connection.
Import: System.Linq;
Step 4: In Web.config, add connection string,
- <connectionStrings>
- <add name="MyCon" connectionString="Data Source=.;Initial Catalog=MyDatabase;Integrated Security=true" providerName="System.Data.SqlClient" />
- </connectionStrings>
Step 5: Finally create an instance of EmployeeDataContext class,
- protected void Application_Start(object sender, EventArgs e)
- {
- EmployeeDataContext Edc = new EmployeeDataContext();
- Employee emp = new Employee()
- {
- EmployeeName = "test Name"
- };
- Edc.Employees.Add(emp);
- Edc.SaveChanges();
- }
Here is the Solution Explorer:
Table has been created:
Hope you like this article, we will get to know about Data Annotations in further articles.
Read more articles on Entity Framework: