I am in开发者_开发技巧serting 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?
- Id will be available in
Object
after you call dc.SaveChanges(); - Another way it's use Guid or some else id that you can generate yourself.
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;
}
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
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?
精彩评论