views:

96

answers:

1

Say you create an object and saving to database by using ADO Entity Framwork as in the code below.

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();
}

How can I retrieve the ID of the newly created object?

Thanks in advance.

+7  A: 

Once you call "SaveChanges()" the entity object should have the ID field filled by the framework.

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.
}

Hope this helps...

Lukasz
That was simple enough... thanks a lot!
ggomez