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

U.S. FDA Accepts Biologics License Application (BLA) for Mylan and Biocon’s Proposed Biosimilar Pegfilgrastim for Review
Mylan N.V. (NASDAQ, TASE: MYL) and Biocon Ltd. (BSE code: 532523, NSE: BIOCON) today announced that ...
eGovernments Foundation Signed MoU with Kozhikode Municipal Corporation for Implementing Building Plan Automation Software in Kozhikode
Bengaluru based eGovernments Foundation has signed an agreement with Kozhikode Municipal Corporation...
Swanbay and FaZe Clan Join Hands to Promote the World's Largest Professional Gaming Team in India
The world’s largest professional gaming team, FaZe Clan, has now partnered with Swanbay; a mobile pl...