Code-first approach we have to create
custom classes and based on those custom classes entity framework can generate
database automatically for us.
POCO :- POCO
class is the class which doesn’t depend on any framework specific base class.
It is like any other normal .net class that is why it is called “Plain Old CLR
Objects” These POCO entities (also known as persistence-ignorant objects)
support most of the same LINQ queries as Entity Object derived entities.
In code First approach we doesn’t
work on designer.tt(EDMX). You have to write POCOs classes for this as before I
explained you about POCO classes. For creating Code First approach in entity
framework First you have to install Entity framework as I shown you in earlier
tutorial. Go to your nugget package manager and search on online as entity framework and
download.
Example for Code first approach.
We will understand code first
approach with an example of an employee where a user able to add employee and
update information of an employee. For this first we have to create classes of
the properties of employee. After that we will design database.
Add a class there you put
these Below properties those are defined
for an employee.
namespace
WindowsFormsApplication1
{
public class Employee
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? DateOfBirth { get; set; }
}
}
Now we have defined
properties of employees. Code first approach needed a Context class .This class is derived from DBContext. DbContext is a Collection of entities. So when we have
to inebriate this class in defined class.
Add a class name is “CodeFirsrApproach.cs”
using System.Data.Entity;
namespace
WindowsFormsApplication1
{
class CodeFirsrApproach : DbContext
{
// we will tell the context
what should be created in the database Add the following line:
public DbSet<Employee> Employees { get; set; }
}
}
DbSet is a collection
of entities.
This ensure us to that it
will contain the collection of all employee information and table employee will
created. Now you check your SQLServer instance and add this below code in
programe.cs class
var person = new Employee
{
FirstName = "Munesh",
LastName = "Sharma",
DateOfBirth = DateTime.Now
};
using (var context = new CodeFirsrApproach())
{
context.Employees.Add(person);
context.SaveChanges();
}
Console.Write("Employee information
saved");
Console.ReadLine();
SaveChanges() is a method
which automatically save the data. So when you will run this application its
automatically save a data in database.
Now you go to your Sql server
database there you see will your tables with and fields. There we no need to pass
any parameter it automatically create table in local machine.