如何在实体框架中获取最近添加的对象的主键?

时间:2011-10-11 22:14:12

标签: sql entity-framework

我不知道是否有这样的事情

`//context.Add(...) stuff...
var primaryKeyOfRecentObjectAddedToDB = context.SaveChanges();`

我只想要数据库为我最近添加的对象提供的主键。

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

一旦保存,您就可以在对象上访问它:

var foo = new Foo { Id = Guid.NewGuid(); }

context.Add(foo);
context.SaveChanges();
var id = foo.Id;

更好的是,为您的ID使用Guid(而不是标识列),并且在访问数据库之前可以访问它。

var foo = new Foo { Id = Guid.NewGuid(); }

var id = foo.Id; // have access to the id here

context.Add(foo);
context.SaveChanges();

答案 1 :(得分:1)

如果您在上下文中有多个类型MyEntity的实体必须插入到数据库中,您可以使用类似的内容(在EF 4.1中):

// save references to the entities which will be added in a local list
var listOfEntitiesToAdd = context.ChangeTracker.Entries()
    .Where(e => e.State == EntityState.Added)
    .Select(e => e.Entity)
    .OfType<MyEntity>()
    .ToList();

// insert the entities, state will change to Unchanged,
// PK property (Id) gets populated
context.SaveChanges();

if (listOfEntitiesToAdd.Count > 0)
{
    // get highest created Id
    int maxId = listOfEntitiesToAdd.Max(e => e.Id);
}

答案 2 :(得分:0)

假设您的主键是您的实体的属性并由DB分配,它将在您执行SaveChanges()后填充:

context.Add(someFoo);
context.SaveChanges();
long myId = someFoo.Id;