Get last added record ID in Entity Framework

<>

This question already has an answer here:

Answers


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.


Once you call database.SaveChanges();, the ID field on the model will be populated with the correct Id. So the simple answer to your question is...

Int16 NewId = credential.ID;

As an aside, unless you're absolutely certain you'll never need to cope with more than 32,767 of any type of record, you're usually better off to use Int for all Id fields (or even Long) - that way you don't need to remember which are Int16 and which are Int. The few bytes you save by halving the length of some Id fields are absolutely negligible unless you're on an embedded system.


Need Your Help

Minimum applications and requirements to develop Asp.Net MVC5 application on Windows 7

c# sql asp.net visual-studio azure

I have been trying to develop an Asp.Net MVC5 application that will use a database and uploaded to Azure but I can not seem to get all the dependencies. The template fails to be able to register a ...

Custom probes for Windows Azure Load-balancer

c# wcf azure azure-virtual-machine azure-vm-role

We are trying to create custom probes for LoadBalanced sets in Windows Azure.