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

c# entity-framework

Question

I am inserting into the database through the "AddObject(Object)" method and I wanted to get the last inserted id of that so i could insert into another table with that last created id. How would I go about doing that? Is the best way of doing this? or is there better way?

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

Accepted Answer

  1. Id will be available in Object after you call dc.SaveChanges();
  2. Another way it's use Guid or some else id that you can generate yourself.
13
3/18/2011 9:43:01 AM

Popular Answer

See the code sample as below:

 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