Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get last inserted id in linq EF

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?

like image 735
anthonypliu Avatar asked Mar 18 '11 09:03

anthonypliu


4 Answers

  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.
like image 60
Andrew Orsich Avatar answered Oct 13 '22 19:10

Andrew Orsich


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;
        }
like image 22
Ashraf Alam Avatar answered Oct 13 '22 18:10

Ashraf Alam


When using the AddObject, and then saving the changes, the Object will have the new Id assigned to it.

So you should be able to see Object.Id containing the new ID

like image 3
Tim B James Avatar answered Oct 13 '22 17:10

Tim B James


I'm imagining you are trying to work out a foreign key concept here. Have you considered using Associations which free you from having to track ids for this purpose?

like image 1
Maverik Avatar answered Oct 13 '22 19:10

Maverik