In this article I will explain with an example, how to insert record in Database using Entity Framework Code First Approach with existing Database in ASP.Net Core Razor Pages.
When the Form is submitted, the value of the submitted Form fields will be fetched and inserted into database using Entity Framework Code First Approach in ASP.Net Core Razor Pages.
Database
I have made use of the following table Customers with the schema as follows. CustomerId is an Auto-Increment (Identity) column.
Note: You can download the database table SQL by clicking the download link below.
Configuring and connecting Entity Framework Code First from database
The very first step is to create an ASP.Net Core Razor Pages project and connect it to the Database using Entity Framework.
Once the Entity Framework is configured and connected to the database table, the Entity Model will be generated with following classes.
Generated Table class
public partial class Customers
{
[Key]
public int CustomerId { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
[Required]
[StringLength(50)]
public string Country { get; set; }
}
Generated Database Context
public partial class CodeFirstContext : DbContext
{
public CodeFirstContext()
{
}
public CodeFirstContext(DbContextOptions<CodeFirstContext> options)
: base(options)
{
}
public virtual DbSet<Customers> Customers { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Data Source=.\\SQL2019;Initial Catalog=CodeFirst;Trusted_Connection=True;");
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customers>(entity =>
{
entity.Property(e => e.Country).IsUnicode(false);
entity.Property(e => e.Name).IsUnicode(false);
});
}
}
Razor PageModel (Code-Behind)
The PageModel consists of following two Handler methods.
Handler method for handling GET operation
This Handler method handles the GET calls, for this particular example it is not required and hence left empty.
Handler method for handling Button Click and POST operation
This Handler method handles the POST call when the Submit Button is clicked and the Form is submitted.
This Handler method accepts an object of the Customers Model class as parameter. The values posted from the Form inside the Razor Page are received through this parameter.
The received values are then inserted into the SQL Server database table using Entity Framework Code First Approach.
The CustomerId of the inserted record is available in the Customers Model object after the SaveChanges method is executed.
Finally, the Customers Model object is set into the Customer public property.
public class IndexModel : PageModel
{
public Customers Customer { get; set; }
public void OnGet()
{
}
public void OnPostSubmit(Customers customer)
{
using (CodeFirstContext context = new CodeFirstContext())
{
context.Customers.Add(customer);
context.SaveChanges();
//Fetch the returned CustomerId.
int id = customer.CustomerId;
this.Customer = customer;
}
}
}
Razor Page (HTML)
Inside the Razor Page, the ASP.Net TagHelpers is inherited.
The Razor Page consists of an HTML Form which has been created using the ASP.Net TagHelpers attributes with the following attribute.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
There is one HTML TextBox field created for capturing value for Name. While for capturing the Country value, a HTML DropDownList (Select) with Country options is created.
There’s also a Submit Button at the end of the Form.
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostSubmit but here it will be specified as Submit when calling from the Razor HTML Page.
When the Button is clicked, the Form is submitted and the Customers class is sent to the Handler Method.
After the Form is submitted, the Customers property returned from the Handler Method is checked for NULL and if it is not NULL then the newly inserted CustomerId is displayed using JavaScript Alert MessageBox.
@page
@model EF_CodeFirst_Insert_Razor_Core.Pages.IndexModel
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form method="post">
<table>
<tr>
<th colspan="2" align="center">Customer Details</th>
</tr>
<tr>
<td>Name: </td>
<td><input type="text" asp-for="Customer.Name" /></td>
</tr>
<tr>
<td>Country: </td>
<td>
<select asp-for="Customer.Country">
<option value="">Please select</option>
<option value="India">India</option>
<option value="China">China</option>
<option value="Australia">Australia</option>
<option value="France">France</option>
<option value="Unites States">Unites States</option>
<option value="Russia">Russia</option>
<option value="Canada">Canada</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" asp-page-handler="Submit" /></td>
</tr>
</table>
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
@if (Model.Customer != null)
{
<script type="text/javascript">
$(function () {
alert("Inserted Customer ID: " + @Model.Customer.CustomerId);
});
</script>
}
</body>
</html>
Screenshots
The Form
Inserted Record in Customers Table
Downloads