How to return the ID field after the insert in Entity Framework ?

There are times when you want to retrieve the ID of the last inserted record when using Entity Framework .

For example ,

Employee emp = new Employee();

emp.ID = -1;

emp.Name = "Senthil Kumar B";

emp.Expertise = "ASP.NET MVC"

EmployeeContext context = new EmployeeContext();

context.AddObject(emp);

context.SaveChanges();

In the above example , if i need to retrieve the ID of the employee that was inserted , all that i need to do is use the emp.ID property once the data is saved as shown below.

Employee emp = new Employee();

emp.ID = -1;

emp.Name = "Senthil Kumar B";

emp.Expertise = "ASP.NET MVC"

EmployeeContext context = new EmployeeContext();

context.AddObject(emp);

context.SaveChanges();

int empID = emp.ID;
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Leave a Reply


x

Interesting BlogPosts to read

Passing Array of Integers to ASP.NET Web API REST Service
You can pass an array of integer to an ASP.NET Web Web API REST service by setting the [FromUri] att...
How to convert black money into white is trending in Google search...
After the Prime Minister Narendra Modi's announcement regarding the demonetization of the 500 rupee ...
Google Announces National Finalists of Doodle4Google Contest 2016
Google India today announced the names of the twelve national finalists of the 8th edition of its an...