In this article I will explain with an example, how to update into
Database using
Entity Framework in ASP.Net.
Database
I have made use of the following table Customers with the schema as follow.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Configuring and connecting Entity Framework to database
HTML Markup
The HTML Markup consists of following controls:
TextBox – For capturing the values of CustomerId, Name and Country.
Button – For updating records.
The Button has been assigned with an OnClick event handler.
<table>
<tr>
<td>CustomerId:</td>
<td>
<asp:TextBox ID="txtCustomerId" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Name:</td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Country:</td>
<td>
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td></td>
<td>
<asp:Button runat="server" Text="Update" OnClick="OnUpdate" /></td>
</tr>
</table>
Updating records into Database using Entity Framework
The following event handler is executed when the Update Button is clicked.
Inside the event handler, CustomerId, Name and the Country values are fetched from their respective TextBoxes.
The CustomerId value is used to reference the Customer record using
Entity Framework.
Once the record is referenced, the values of Name and Country are updated and the changes are updated into the Customers table.
Finally, based on whether record is updated or not an appropriate message is displayed in
JavaScript Alert Message Box using
RegisterStartupScript method.
C#
protected void OnUpdate(object sender, EventArgs e)
{
using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
{
int customerId = int.Parse(txtCustomerId.Text);
var updateCustomer = (from customer in entities.Customers
where customer.CustomerId == customerId
select customer).FirstOrDefault();
if (updateCustomer != null)
{
updateCustomer.Name = txtName.Text;
updateCustomer.Country = txtCountry.Text;
entities.SaveChanges();
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Customer record updated.');", true);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Customer not found.');", true);
}
}
}
VB.Net
Protected Sub OnUpdate(sender As Object, e As EventArgs)
Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
Dim customerId As Integer = Integer.Parse(txtCustomerId.Text)
Dim updateCustomer = (From customer In entities.Customers
Where customer.CustomerId = customerId
Select customer).FirstOrDefault()
If updateCustomer IsNot Nothing Then
updateCustomer.Name = txtName.Text
updateCustomer.Country = txtCountry.Text
entities.SaveChanges()
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Customer record updated.');", True)
Else
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Customer not found.');", True)
End If
End Using
End Sub
Screenshot
Downloads