ADO.NET Entity Framework(EF)

EF(Entity Framework) is object -relational mapper(ORM) that enable .Net developer to work with relational data using domain specific object. History: First version released with .Net 3.5 in 2008.
Reduce the data access code.
Tables become classes.
Columns as properties.

Example:
Go to project right click and add new item ADO.Net Entity Data Model.
An .edmx file get attached then use wizard to assign DB connection and select tables and SPs.
Lets consider the file added names as FirstEF.edmx and in DB we have Employee table with columns name as FirstName, LastName , Address, City .

Code snippet To Add new employee entry in DB.
FirstEFEntities db = new FirstEFEntities();– This is called the ObjectContext class associated with each .edmx file. Appended Entities with the file name and holds all the major available operations of EF.

Employee objEmp = new Employee();
objEmp.FirstName = txtFirstName.Text;
objEmp.LastName = txtLastName.Text;
objEmp.Address = txtAddress.Text;
objEmp.City = txtCity.Text;

db.Employees.AddObject(objEmp);
db.SaveChanges();

Next is LINQ to Entities: Could be used to read and update LINQ provides compile time support for query validation.
To read:
var empQuery = from emp in db.Employees
select emp;
List empList = empQuery.ToList();
To Update:
var empQuery = from emp in db.Employees
where emp.EmpId == empId(Local variable)
select emp;
Employee objEmp = empQuery.Single();
db.SaveChanges();
To Delete:
db.Employees.Attach(objEmp);– Attach to ObjectContext class.
db.Employees.DeleteObject(objEmp);
db.SaveChanges();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s