Entity Framework is ORM .net framework, which is used to
update, create or delete record from table.
As Per MSDN “Entity Framework (EF) is an
object-relational mapper that enables .NET developers to work with relational
data using domain-specific objects”
EntityFramework
works as a layer between database and business layer (application code) and
entity framework maps each database table to entity class ( C# CLR class) and
with help of this entity class, developer can perform SQL DML operation like
create, modify and delete on mapped database table.
Create Record:
Below code shows how to add new record of department entity
Department department = newDepartment()
{
Name = "Admin"
};
DBContext DbContext = new DBContext ();
DbContext.Departments.Add(department);
DbContext.SaveChanges();
As you can see, we are performing below steps to create a new
record of department with department name ‘Admin’
- Create new object of Department and set department Name to “Admin”.
- Create new DBContext Object.
- Add new department object to Department entity set.
- Call saveChanges() method of DBContext Object to add new department record and this method parse the entity graph and generate SQL script and execute on connected database.
Update Record:
Below code shows how to modified the existing record of
department entity
DBContext DbContext = new DBContext ();
Department department =
DbContext.Departments.FirstOrDefault(d => d.Name == "Admin");
department.Code = "A";
DbContext.SaveChanges();
As you can see, below steps are being used to update the
existing record of department entity
- Create new DBContext Object.
- Fetch the existing record of department and load into local memory.
- Update desired fields or properties of department record.
- Call saveChanges() method of DBContext Object to update department record and this method parse the entity graph and generate SQL script
Delete Record:
Below code shows how to delete the existing record of
department entity
DBContext DbContext = new DBContext ();
Department department =
DbContext.Departments.FirstOrDefault(d => d.Name == "Admin");
DbContext.Departments.Remove(department);
DbContext.SaveChanges();
As you can see, we are performing below steps to delete the
existing record of department entity
- Create new DBContext Object.
- Load the existing record of department into memory.
- Remove the record from Department entity Set.
- Call SaveChanges() method of DBContext Object to delete the attached department record and this method parse the entity graph and generate SQL script and execute on the connected database.
Thanks for visiting !!
Other Entity framework related Links:
No comments:
Post a Comment