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

County Championship Cricket SURREY V ESSEX Live streaming
Surrey takes on Essex in the Specsavers County Championship Division 1 Cricket League from April 11 ...
Viral Video - Man Lifted in Air on Umbrella
This is one of the video that has gone viral on social media from last few days where a man is seen ...
Ericsson and RJio accelerate India’s 5G story by developing live 5G use cases for India
Ericsson (NASDAQ: ERIC) and Reliance Jio Infocomm Ltd (RJio) today unveiled jointly developed 5G use...