In this article I will explain with an example, how to insert into
Database using
Entity Framework in ASP.Net.
Database
I have made use of the following table Customers with the schema as follow.
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 Name to be inserted.
DropDownList – For selecting Country name to be inserted.
Button – For inserting the records.
The Button has been assigned with an OnClick event handler.
<table cellpadding="0" cellspacing="0">
<tr>
<td>Name: </td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>Country: </td>
<td>
<asp:DropDownList ID="ddlCountries" runat="server">
<asp:ListItem Text="Please select" Value="" />
<asp:ListItem Text="United States" Value="United States"></asp:ListItem>
<asp:ListItem Text="India" Value="India"></asp:ListItem>
<asp:ListItem Text="France" Value="France"></asp:ListItem>
<asp:ListItem Text="Russia" Value="Russia"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td></td>
<td>
<asp:Button runat="server" Text="Submit" OnClick="OnSubmit" /></td>
</tr>
</table>
Inserting records into Database using Entity Framework
The following event handler is executed when the Submit Button is clicked.
Inside the event handler, name and the country values are fetched from their respective Controls and then passed through an object of Customer class to the
Add method of Customers properties using
Entity Framework.
Finally, the
CustomerId of the submitted record is fetched and displayed in
JavaScript Alert Message Box using
RegisterStartupScript method.
C#
protected void OnSubmit(object sender, EventArgs e)
{
using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
{
Customer customer = new Customer
{
Name = txtName.Text,
Country = ddlCountries.SelectedItem.Text
};
entities.Customers.Add(customer);
entities.SaveChanges();
int id = customer.CustomerId;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Inserted Customer ID: " + id + "');", true);
}
}
VB.Net
Protected Sub OnSubmit(sender As Object, e As EventArgs)
Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
Dim customer As Customer = New Customer With {
.Name = txtName.Text,
.Country = ddlCountries.SelectedItem.Text
}
entities.Customers.Add(customer)
entities.SaveChanges()
Dim id As Integer = customer.CustomerId
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Inserted Customer ID: " & id & "');" , True)
End Using
End Sub
Screenshot
Record after Insert in Database
Downloads