Get Record ID in Entity Framework 5 after insert

399 views Asked by At

I realize this must be a relatively simple thing to do, but I'm not getting what I'm looking for with Google.

I need to get the record ID of the record I just saved using the Entity Framework. With SQL queries we used "Select @@IDENTITY as 'Identity';"

If anyone can help it would be greatly appreciated.

1

There are 1 answers

0
Miguel Martinez On BEST ANSWER

The default behavior of Entity Framework is it sets identity fields on entities from the database right after SaveChanges is called.

In the following sample code, before SaveChanges is called, my employee has a default ID of 0. After SaveChanges my employee has a generated ID of 1.

using (TestDbEntities context = new TestDbEntities())
{
    Employee e = new Employee ();
    e.FirstName = "John";
    e.LastName = "Doe";
    context.Employee.Add(e);
    context.SaveChanges();
    Console.WriteLine("Generated ID: {0}", e.ID);
    Console.ReadKey();
}