假设您使用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. }
希望这可以帮助…