Get Id of last Inserted Record using Entity Framework in ASP.Net Core MVC

Last Reply one month ago By dharmendr

Posted one month ago

How to get ID of last inserted record using using entity framework in ASP.Net Core MVC

Posted one month ago Modified on one month ago

Hi rani,

Check this example. Now please take its reference and correct your code.


I have made use of the following table Customers with the schema as follows. CustomerId is Identity column.

I have already inserted few records in the table.

You can download the database table SQL by clicking the download link below.

Download SQL file


public class Customer
    public int  CustomerId{ get; set; }
    public string Name { get; set; }
    public string Country { get; set; }


public class HomeController : Controller
    private DBCtx Context { get; }
    public HomeController(DBCtx _context)
        this.Context = _context;

    public IActionResult Index()
        ViewBag.Customers = this.Context.Customers.ToList();
        return View();

    public IActionResult Index(Customer customer)
        ViewBag.Id = customer.CustomerId;
        ViewBag.Customers = this.Context.Customers.ToList();
        return View();


@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@using Last_Id_Entity_Framework_Core_MVC.Models
@model Customer
    Layout = null;

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <form asp-action="Index" asp-controller="Home" method="post">
        Name: <input type="text" asp-for="@Model.Name" />
        <br /><br />
        Country: <input type="text" asp-for="@Model.Country" />
        <br /><br />
        <input type="submit" id="btnSubmit" value="Submit" />
    @if (ViewBag.Customers != null)
        <hr />
                @foreach (Customer customer in ViewBag.Customers)
    @if (ViewBag.Id != null)
        <script type="text/javascript">
            window.onload = function () {
                alert('Last Inserted Id : '+'@ViewBag.Id');