代码之家  ›  专栏  ›  技术社区  ›  Guillermo Gomez

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

  •  8
  • Guillermo Gomez  · 技术社区  · 15 年前

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

    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 回复  |  直到 15 年前
        1
  •  13
  •   Lukasz    15 年前

    调用“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.
    }
    

    希望这有帮助…