Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Return the ID Field After an Insert in Entity Framework?

DZone's Guide to

How to Return the ID Field After an Insert in Entity Framework?

· Database Zone
Free Resource

Whether you work in SQL Server Management Studio or Visual Studio, Redgate tools integrate with your existing infrastructure, enabling you to align DevOps for your applications with DevOps for your SQL Server databases. Discover true Database DevOps, brought to you in partnership with Redgate.

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;


It’s easier than you think to extend DevOps practices to SQL Server with Redgate tools. Discover how to introduce true Database DevOps, brought to you in partnership with Redgate

Topics:
dotnet ,database ,how-to ,microsoft ,tools ,.net & windows ,c-sharp ,ef

Published at DZone with permission of Senthil Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}