获取最近创建的实体的ID - ADO实体框架

时间:2010-01-02 01:25:50

标签: c# asp.net-mvc entity-framework

假设您使用ADO Entity Framwork创建一个对象并保存到数据库,如下面的代码所示。

private void CreateAddress(BizObjects.Address address)
{
    var entity = new EntityFramework.Address();

    entity.Line1 = address.Line1;
    entity.Line2 = address.Line2;
    entity.City = address.City;
    entity.State = address.State;
    entity.ZipCode = address.ZipCode;

    _entities.AddToAddress(entity);
    _entities.SaveChanges();
}

如何检索新创建的对象的ID?

提前致谢。

1 个答案:

答案 0 :(得分:13)

一旦调用“SaveChanges()”,实体对象应该具有框架填充的ID字段。

private void CreateAddress(BizObjects.Address address)
{
    var entity = new EntityFramework.Address();

    entity.Line1 = address.Line1;
    entity.Line2 = address.Line2;
    entity.City = address.City;
    entity.State = address.State;
    entity.ZipCode = address.ZipCode;

    _entities.AddToAddress(entity);
    _entities.SaveChanges();

    address.Id = entity.Id; // At this point the entity object will have the value of the Id field.
}

希望这会有所帮助......