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 MVC.
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 MVC.
 
 
Database
I have made use of the following table Customers with the schema as follows. CustomerId is an Auto-Increment (Identity) column.
ASP.Net Core: Insert Data into Database using Entity Framework Code First Approach
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Configuring and connecting Entity Framework Code First from database
The very first step is to create an ASP.Net Core MVC Application and connect it to the Database using Entity Framework.
Note: For more details, please refer my article ASP.Net Core MVC: EntiyFramework Code First Approach with Existing Database.
 
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);
        });
    }
}
 
 
Controller
The Controller consists of the following two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling POST operation for Inserting
The Action method for POST operation accepts an object of the Customers Model class as parameter. The values posted from the Form inside the View are received through this parameter.
The received values are then inserted into the 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 returned back to the View.
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Index(Customers customer)
    {
        using (CodeFirstContext context = new CodeFirstContext())
        {
            context.Customers.Add(customer);
            context.SaveChanges();
 
            // Fetch the returned CustomerId.
            int id = customer.CustomerId;
        }
 
        return View(customer);
    }
}
 
 
View
Inside the View, in the very first line the Customers Model class is declared as Model for the View.
The View consists of an HTML Form which has been created using the Razor Tag attributes with the following attributes.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
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 and when the Button is clicked, the Form is submitted.
After the Form is submitted, the Customers Model returned from the Controller is checked for NULL and if it is not NULL then the newly inserted CustomerId is displayed using JavaScript Alert MessageBox.
@model EF_CodeFirst_Insert_MVC_Core.Models.Customers
@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" asp-action="Index" asp-controller="Home">
        <table>
            <tr>
                <th colspan="2" align="center">Customer Details</th>
            </tr>
            <tr>
                <td>Name: </td>
                <td><input type="text" asp-for="Name" /></td>
            </tr>
            <tr>
                <td>Country: </td>
                <td>
                    <select asp-for="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" /></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 != null)
    {
        <script type="text/javascript">
            $(function () {
                alert("Inserted Customer ID: " + @Model.CustomerId);
            });
        </script>
    }
</body>
</html>
 
 
Screenshots
The Form
ASP.Net Core: Insert Data into Database using Entity Framework Code First Approach
 
Inserted Record in Customers Table
ASP.Net Core: Insert Data into Database using Entity Framework Code First Approach
 
 
Downloads