Get last added record ID in Entity Framework c# entity-framework


I'm registering a new client in my database, and when that operation finishes I want to show a detail view for that new client. The problem is I'm not finding the way to send to the Details action method the ID of the recently added client.

I'm working on this code:

public ActionResult Register(ClientModel credential)

        return RedirectToAction("Details", //Here is my problem, because sending credential.ID gives me an error as far as credential doesn't have an ID due it's not a database record.;
        return View();

This is mi ClientModel:

public class ClientModel
    public Int16 ID { get; set; }

    public String Name { get; set; }

    public String Address { get; set; }

    public String EmailAddress { get; set; }

    public String Phone { get; set; }

    public virtual ICollection<UserModel> Users { get; set; }

Could someone bring light to my path?


Got an answer, which I would like to discuss:

return RedirectToAction("Details", new { ID = credential.ID });

This solution worked, but now the question could be, is this the better solution, or should I use 2 classes as commented in @Basic's answer?

2/1/2014 3:49:58 PM

Accepted Answer

Entity Framework will automatically load the last inserted id to populate the primary key column of the inserted entity:

var customer = new Customer { Name = "Steven" };



var id = customer.Id;

Note that the Id property only gets populated after calling SaveChanges() in case the StoreGeneratedPattern attribute is set to "Identity" or "Computed" for the auto-incremented ID column in the Storage part of the model.

7/8/2019 7:36:52 AM

Popular Answer

Anyhow if you need the the id for some any other purpose ... calling EF Insert Method for some entity automatically returns the currently inserted row id ...

var rowId=db.Insert(Entity); 

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow