locked
how to return id for newly created table in same method? RRS feed

  • Question

  • User1655654435 posted

    Hi, i have a controller that creates a table using EF with automated value for id.

    var cust = new Cutomer
    {
        Name = "James",
        Description = "Believs in ghosts"
    }
    
    _context.Customer.Add(cust);
    await _context.SaveChangesAsync();

    but i would like to return the created id value for this table so i could go on to the newly created page.

    is this possible? Could i just return RedirectToAction(nameof(YourProfile), new { id = cust.Id} )

    I can't test it where I am right now because I don't have windows and i don't know how to create db on mac.

    Monday, April 20, 2020 8:14 AM

Answers

  • User-18289217 posted
    var cust = new Cutomer
    {
        Name = "James",
        Description = "Believs in ghosts"
    }
    
    _context.Customer.Add(cust);
    await _context.SaveChangesAsync();
    
    // get the newly created customer ID
    var custId = cust.Id;

    HTH

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 20, 2020 8:17 AM

All replies

  • User-18289217 posted
    var cust = new Cutomer
    {
        Name = "James",
        Description = "Believs in ghosts"
    }
    
    _context.Customer.Add(cust);
    await _context.SaveChangesAsync();
    
    // get the newly created customer ID
    var custId = cust.Id;

    HTH

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, April 20, 2020 8:17 AM
  • User1655654435 posted

    But how does this happen? is it not the db that creates the new id? so the reference to the customer object is actually updated as well after the insertion?

    Monday, April 20, 2020 8:56 AM
  • User-18289217 posted

    When auto-generated Ids are used (like IDENTITY in MS SQL) EF by default follows each INSERT with SELECT SCOPE_IDENTITY() and it will be automatically filled for you

    Monday, April 20, 2020 9:35 AM
  • User753101303 posted

    Hi,

    EF knows which values are generated on the db side (either following default convention or explicit EF configuration) and does behind the scene what you would do by hand for reading back those server side generated values.

    Monday, April 20, 2020 9:44 AM