c# – 获取最近创建的实体的ID – ADO实体框架

前端之家收集整理的这篇文章主要介绍了c# – 获取最近创建的实体的ID – ADO实体框架前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设您使用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?

提前致谢.

解决方法

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

希望这可以帮助…

原文链接:https://www.f2er.com/csharp/94282.html

猜你在找的C#相关文章