Sunday, 29 July 2012

Entity Framework


What is Entity Framework ?


  • Entity Framework based on ORM (object relation mapping).
  • Entity Framework enables developers to work with relational data, eliminate the need for most of the data access plumbing code that developers usually need to write.
  • It uses LINQ (Language Integrated Query) to retrieve and manipulate data as strongly typed objects.

 

Advantages


  • One common syntax "LINQ" for all object queries.
  • Fast
  • Easy to implement.
  • Less coding required.

Now, take an example for How to use it:

Insertion, Updation and Deletion with Entity Framework


Step:1 First, create a ASP.Net empty web application named "WebAppEntity". Right click on solution, add new item > add ADO.NET Data Entity Model named it as "BusinessObjects.edmx"




Now check your Web.config file, it will create connection string automatically. And check your BusinessObjects.designer.cs also, It looks like:

















Open/Expand Contexts,































Step:2 File > Add > New Project > ASP.NET Empty Web Application named "Entity Framework".

  • Copy connection string of "WebApp Entity Web.config file" to "Entity Framework Web.config file".

  • Add two "Web Refrences" in "Entity Framework"
                       1. Projects > "WebAppEntity"
                       2. System.Web.Entity

  • Create a aspx page named "EntityFirst.aspx" for create, update and delete the records.

Now, Solution looks like:



Step:3 Now Add a code into "EntityFirst.aspx" and  "EntityFirst.aspx.cs"     

Add three button for save, update and delete in EntityFirst.aspx like:

<asp:Button ID="btnsave" runat="server" Text="Save" OnClick="btnsave_Click" />
<asp:Button ID="btnupdate" runat="server" Text="Update" OnClick="btnupdate_Click" />
<asp:Button ID="btndelete" runat="server" Text="Delete" OnClick="btndelete_Click" />


Now, add code in code behind like:

using  WebAppEntity;


LeadManagementTestEntities LeadDB = new LeadManagementTestEntities();

protected void btnsave_Click(object sender, EventArgs e)
{
aaa objaa = new aaa();
objaa.user = "Name";
objaa.city = "Gurgaon";
objaa.designation = "Software Engineer";
LeadDB.aaas.AddObject(objaa);
LeadDB.SaveChanges();
lblmsg.Text =
"Record saved successfully";
}

protected void btnupdate_Click(object sender, EventArgs e)
{
aaa objaa = LeadDB.aaas.SingleOrDefault(p => p.user == "Ruchi");
objaa.city = "Delhi";
LeadDB.SaveChanges();
lblmsg.Text =
"Record updated successfully";
}

protected void btndelete_Click(object sender, EventArgs e)
{
aaa objaa = LeadDB.aaas.SingleOrDefault(p => p.user == "Name");
LeadDB.aaas.DeleteObject(objaa);
LeadDB.SaveChanges();
lblmsg.Text =
"Record deleted successfully";

}



Now, we are done. Run the application and test it.

2 comments: