如何在Entity Framework中查找最后插入的行的标识?

Vai*_*ain 39 .net entity-framework

我在多个表中插入数据.我需要知道表中最后插入的(自动递增的)ID.我需要在其他表中将它用作Foriegn Key.

总之,我需要替代@@IdentityT-Sql.

Ste*_*ven 87

实体框架将自动加载最后插入的ID以填充插入实体的主键列:

var customer = new Customer { Name = "Steven" };

context.AddObject(customer);

context.SaveChanges();

var id = customer.Id;
Run Code Online (Sandbox Code Playgroud)

请注意,Id只有在模型的存储部分中为属性设置为"标识"或"已计算"自动递增的ID列时,才会在调用后填充SaveChanges()StoreGeneratedPattern属性.

  • 仅当StoreGeneratedPattern属性设置为模型的存储部分中自动递增ID列的"Identity"或"Computed"时,这才是正确的. (6认同)