HomeCSharpHow to return the ID field after the insert in Entity Framework ?

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;

Leave a Reply

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...