As we all know, Entity Framework is an enhancement to an existing ADO.Net technique and ORM framework we used for Microsoft technologies.
There are the following 3 approaches we use during application development.
- Code First
- Model First
- Database First (DB first)
So, in this article, we will learn how to develop a simple C# application using the Entity Framework code-first approach.
You need Visual Studio 2010/2012/2013 and SQL Server to learn this.
Create a new C# Class Library project named "CodeFirstLibrary". Add a new class named "Employee" to the project. (You can use Entity Framework 4.1/4.3/5.0/6.0 for this example.)
Employee Class
public class Employee
{
public Employee()
{
}
public int EmployeeID { get; set; }
public string Name { get; set; }
}
Add a new class derived from the DBContext class with a DbSet property for the Employee class.
(References needed: System.Data.Entity and EntityFramework).
public class Context : DbContext
{
public Context() : base()
{
}
public DbSet<Employee> Employees { get; set; }
}
Add a new console application project named "CodeFirstConsole" to this solution so that we can test these classes.
using (var ctx = new Context())
{
Employee emp = new Employee() { name = "Prashant" };
ctx.Employees.Add(emp);
ctx.SaveChanges();
}
Set "CodeFirstConsole" as the startup project. Run the application and see what is happening. It has successfully stored the Employee information in the database.
Surprised?
Where is the database? How was it created? What are the tables created, and what is the table structure?
This is the beauty of Code First for the Entity Framework. It creates the database based on a parameter passed in the base constructor of your context class. We have not passed any parameters so it will create a “CodeFirstLibrary.Context” database in the local SQLEXPRESS.
Some Important points to note here are,
- Code-first will create a table in the database. The "Employees’ table is created based on the Employee class.
- Code First APIs create a PrimaryKey in the table if the class has either an “Id” or ClassName + “Id” property. For example, the Employee class has the “EmployeeID” property so it will create EmployeeID as the PK column.
- It will also create other columns with the same name and datatype as property names as shown in the following screenshot.
So, using EF Code First, we can create applications that will generate a DB at runtime.