Get last added record ID in Entity Framework

asp.net-mvc, c#, entity-framework

Solution

When you call `SaveChanges()`, `credential.ID`, if an auto number in the database and setup in the EF model, should be populated. You could try reloading an element like mentioned in Entity Framework 4.1 DbSet Reload.

In your scenario above, you are adding a new client, so you need to convert the client model to client like:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(ClientModel credential)
{
    var client = new Client
    {
       Name = model.Name,
       EmailAddress = model.EmailAddress,
       .
       .
    };

    db.Clients.Add(client);
    db.SaveChanges();

    model.ID = client.ID;

    return View(model);
}

And then the ID will be returned with the model.

Problem

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: ``` [HttpPost] [ValidateAntiForgeryToken] public ActionResult Register(ClientModel credential) { if(ModelState.IsValid) { database.Clients.Add(credential); database.SaveChanges(); 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.; } else { return View(); } } ``` This is mi `ClientModel`: ``` [Table("Clients")] public class ClientModel { [Key] public Int16 ID { get; set; } [Required] public String Name { get; set; } public String Address { get; set; } [EmailAddress] public String EmailAddress { get; set; } [Phone] public String Phone { get; set; } public virtual ICollection<UserModel> Users { get; set; } } ``` Could someone bring light to my path? EDIT: 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?

Original source

Related problems