开发者

Getting ID of recently created entity - ADO Entity Framework

开发者 https://www.devze.com 2022-12-15 10:40 出处:网络
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)

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 = add开发者_如何学编程ress.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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号