In Linq EF, how do I retrieve the latest entered id?

c# entity-framework

Question

I needed to know the latest generated id of an object I was adding to the database using the "AddObject(Object)" function so I could add it to another table. What would be the best way to achieve that? Is this the best approach? or is there an alternative?

1
9
3/18/2011 10:37:45 AM

Accepted Answer

  1. Id will be offered inObject after the call to dc.SaveChanges();
  2. Use Guid or any ID that you create on your own is another option.
13
3/18/2011 9:43:01 AM

Popular Answer

See the following code sample:

 public virtual int CreateNewEmployee(Employee newEmployee)
        {
            if (newEmployee.EntityState == EntityState.Detached)
                _DatabaseContext.Employees.Attach(newEmployee);

            _DatabaseContext.ObjectStateManager.ChangeObjectState(newEmployee, EntityState.Added);

            int numberOfAffectedRows = _DatabaseContext.SaveChanges();

            return newEmployee.EmployeeId;
        }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow