Entity Framework
Before going through this blog you must be familiar with basic of Asp.net application and Linq expressions.
What is Entity Framework?
Entity framework is ORM(Object Relational Mapping) which allows to create object and enables us to work with relational data eliminating the need of data access code which we usually need to write. Data can be retrieved and manipulated in form of strongly typed objects.
It is designed to enable developers to create data access applications by programming against a conceptual application model instead of programming directly against a relational storage schema. The goal is to decrease the amount of code and maintenance required for data-oriented applications.
Requirements
1.ADO.NET Entity Framework requires .NET Framework 3.5 Service Pack 1 or higher.
2.Visual Studio 2008 Service Pack 1 or higher.
3.For Entity Framework 6, you will also need a NuGet Visual Studio extension installed since it is used for adding EntityFramework NuGet package.
Approaches to Entity FrameWork-:
1.DataBase First
In the database first approach, we are going to create the entity framework from an existing database. We uses functionality, such as the model/database sync and the code generation.
Features-:
An existing database can be used to create model.
Code can be auto-generated.
Extensible using partial classes/ T4 templates.
The developer can update the database manually.
There is a very good designer(EDMX), which sync with the underlining database.
2.Model First
In the Model First approach, the database model is created first using the ORM designer in Visual Studio. Once the model consisting of entities and relationships has been designed, the physical database will be generated from the model.
Features-:
Good support with EDMX designer to create model.
We can visually create the database model and can apply associations and relationships among database.
EF generates the Code and database script to create database.
Extensible through partial classes.
We can modify the model and update the generated database accordingly.
3.Code First
In Code-First Approach, we create the classes first and then generate the database from the classes directly. In code first, we don't have EDMX designer.
Features-:
There is full control of the model from the Code.
No manual intervention to DB is required.
The database is used for data only.
Advantages-:
1.One common syntax (LINQ)for all object queries whether it is database or not.
2.It is fast and straight forward using LINQ/FE objects for Create/Read/Update/Delete.
3.Less coding required to perform complex tasks.
4.It keeps a good performance when you work with a small / middle domain model
Dis-advantages-:
1.If there is change in database schema then we have to update the solution as well to reflect the changes.
2.Mapping of object becomes difficult with huge data.
3.It's limited when you work with a huge domain model.
When to Use?
An ORM is only useful if you want to work with data in an object-oriented way.
Here is Simple example of Entity Framework(Using Database First Approach).
EmpLogIn.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EmpLogIn.aspx.cs" Inherits="WebApplication1.EmpLogIn" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<div>
<asp:Label runat="server" ID="lblMessage" Text=" " BackColor="Peru" />
</div>
<form id="form1" runat="server">
<div style="background-color: aqua">
<table>
<tr>
<th colspan="2">Employee LogIn</th>
</tr>
<tr>
<td>
<asp:Label runat="server" Text="Userame"></asp:Label></td>
<td>
<asp:TextBox runat="server" ID="txtUserName"></asp:TextBox></td>
</tr>
<tr>
<td>
<asp:Label runat="server" Text="Password"></asp:Label></td>
<td>
<asp:TextBox runat="server" ID="txtUserPassword" TextMode="Password"></asp:TextBox></td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Insert" OnClick="btnSubmit_Click" /></td>
</tr>
</table>
</div>
<div style="padding: 30px">
</div>
<div style="background-color: aqua">
<asp:Button ID="btnViewDetails" runat="server" Text="ViewDetails" OnClick="btnViewDetails_Click" />
<asp:GridView runat="server" AutoGenerateColumns="false" ID="gv_EmployeeDetails">
<Columns>
<asp:BoundField HeaderText="Id" DataField="UserId" />
<asp:BoundField HeaderText="Name" DataField="UserName" />
</Columns>
</asp:GridView>
</div>
<div style="padding: 30px">
</div>
<div style="background-color: aqua">
<asp:Label runat="server" Text="Enter Id to Update Or Delete"></asp:Label>
<table>
<tr>
<th colspan="2">Update Employee Record</th>
</tr>
<tr>
<td>
<asp:Label runat="server" Text="UserId"></asp:Label></td>
<td>
<asp:TextBox runat="server" ID="txtUserId" placeholder="Enter User ID"></asp:TextBox></td>
</tr>
<tr>
<td>
<asp:Label runat="server" Text="UserName"></asp:Label></td>
<td>
<asp:TextBox runat="server" ID="txtUserNameEdit"></asp:TextBox></td>
</tr>
<tr>
<td>
<asp:Label runat="server" Text="Password"></asp:Label></td>
<td>
<asp:TextBox runat="server" ID="txtPasswordEdit" TextMode="Password"></asp:TextBox></td>
</tr>
<tr>
<td>
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" /></td>
<td>
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
</td>
</tr>
</table>
</div>
</form>
<div style="padding: 30px">
</div>
</body>
</html>
EmpLogIn.aspx.cs
namespace WebApplication1
{
public partial class EmpLogIn : System.Web.UI.Page
{
DNNDemoPriyankEntities db = new DNNDemoPriyankEntities();
protected void Page_Load(object sender, EventArgs e)
{
}
public void BindGrid()
{
List<Func_GetEmployees_Result> employeeDetails = new List<Func_GetEmployees_Result>();
employeeDetails = db.Func_GetEmployees().ToList();
gv_EmployeeDetails.DataSource = employeeDetails;
gv_EmployeeDetails.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
EmployeeDetail employeeDetail = new EmployeeDetail();
employeeDetail.UserName = txtUserName.Text;
employeeDetail.Password = txtUserPassword.Text;
db.EmployeeDetails.Add(employeeDetail);
db.SaveChanges();
BindGrid();
txtUserName.Text = "";
lblMessage.Text = "Inserted Successfully";
}
protected void btnViewDetails_Click(object sender, EventArgs e)
{
BindGrid();
}
protected void btnUpdate_Click(object sender,EventArgs e)
{
int userId = Convert.ToInt32(txtUserId.Text);
var query = from emp in db.EmployeeDetails where emp.UserId == userId select emp;
EmployeeDetail empdetail = query.Single();
empdetail.UserName = txtUserNameEdit.Text;
empdetail.Password = txtPasswordEdit.Text;
db.SaveChanges();
BindGrid();
txtUserNameEdit.Text = "";
txtUserId.Text = "";
lblMessage.Text = "Updated Successfully";
}
protected void btnDelete_Click(object sender, EventArgs e)
{
int userId = Convert.ToInt32(txtUserId.Text);
EmployeeDetail empdetail = new EmployeeDetail() { UserId=userId};
db.EmployeeDetails.Attach(empdetail);
db.EmployeeDetails.Remove(empdetail);
db.SaveChanges();
BindGrid();
txtUserId.Text = "";
lblMessage.Text = "Deleted Successfully";
}
}
}
DNNDemoPriyankEntities db = new DNNDemoPriyankEntities();
Object of class which defines the classes that need to be converted to database tables.
EmployeeDetail employeeDetail = new EmployeeDetail();
The class which which represents our database table.
CREATE
protected void btnSubmit_Click(object sender, EventArgs e)
{
EmployeeDetail employeeDetail = new EmployeeDetail();
employeeDetail.UserName = txtUserName.Text;
employeeDetail.Password = txtUserPassword.Text;
db.EmployeeDetails.Add(employeeDetail);
db.SaveChanges();
BindGrid();
txtUserName.Text = "";
lblMessage.Text = "Inserted Successfully";
}
This is event handler of button "Insert". on clicking insert we have created an instance of EmployeeDetail and set its UserName and password to values inserted in textboxes. As our class is strongly bind
to database table so, it will automatically create a new row in database and set attribute UserName and Password to object's UserName and Password respectively by simply calling function Add() with parameter object.
Now, if you see table EmployeeDetail it will display the new row. As you can see it is quite simple to insert data as compared to insertion using SqlDataReader and SqlDataAdapter.
Note-:It will not insert the values to table if you remove the line db.SaveChanges(). db.SaveChanges() is used to refresh the table.
READ
public void BindGrid()
{
List<Func_GetEmployees_Result> employeeDetails = new List<Func_GetEmployees_Result>();
employeeDetails = db.Func_GetEmployees().ToList();
gv_EmployeeDetails.DataSource = employeeDetails;
gv_EmployeeDetails.DataBind();
}
Here I have used stored procedure to return list of row in EmployeeDetail table. db.Func_GetEmployees() is a call to stored procedure "dbo.GetEmployees" and will return a list of rows in database table.
UPDATE
protected void btnUpdate_Click(object sender,EventArgs e)
{
int userId = Convert.ToInt32(txtUserId.Text);
var query = from emp in db.EmployeeDetails where emp.UserId == userId select emp;
EmployeeDetail empdetail = query.Single();
empdetail.UserName = txtUserNameEdit.Text;
empdetail.Password = txtPasswordEdit.Text;
db.SaveChanges();
BindGrid();
txtUserNameEdit.Text = "";
txtUserId.Text = "";
lblMessage.Text = "Updated Successfully";
}
This is event handler of button "Update". Here,"query" is in LINQ format and query.Single() will return an instance of table that represents database table. As our database table is strongly bind
with EmployeeDetail so employeeDetail will contain the value of row returned from query. We will be directly updating the UserName and Password with the value of textboxes and will call SaveChanges()
to reflect changes.
Delete
protected void btnDelete_Click(object sender, EventArgs e)
{
int userId = Convert.ToInt32(txtUserId.Text);
EmployeeDetail empdetail = new EmployeeDetail() { UserId=userId};
db.EmployeeDetails.Attach(empdetail);
db.EmployeeDetails.Remove(empdetail);
db.SaveChanges();
BindGrid();
txtUserId.Text = "";
lblMessage.Text = "Deleted Successfully";
}
This is event handler of button "Delete". Simply add userId to UserId of object,attach object using Attach() and remove the object using Remove(). Remove() will remove the row from the database table
on the basis of object's UserId.
0 Comment(s)