Get last added record ID in Entity Framework

asp.net-mvc c# entity-framework

Question

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?

1
8
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" };

context.AddObject(customer);

context.SaveChanges();

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.

88
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





Related

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