Platinum Partner
dotnet,database,how-to,microsoft,tools,.net & windows,c-sharp,ef

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;


Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

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

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}