How to Return the ID Field After an 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;
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)





Comments
Lukasz Zwierko replied on Fri, 2013/02/22 - 6:31am
@dzone: guys can you please posting such a trivial blog posts? Seriously, the articles level on this zone has seriously decreased over the last 2 years. What next? "hello world" examples? Come on..
Saying that - I have nothing against this concrete post, some people may find it valuable, but DZone should be aming for Eric Lippert kind of bloggers or else just rename it to tutorial.dzone.com or such.
Robson Castilho replied on Sun, 2013/02/24 - 8:51pm
in response to:
Lukasz Zwierko
Totally agree.
I didn't believe my eyes when I first read it...
Gonzalo Arrivi replied on Wed, 2013/02/27 - 7:59am
I agree. I clicked this post because I thougth there was something more about this, so you can imagine my surprise.
I think this kind of posts would be really cool in a tutorial section, just as @Lukasz said.