假设您使用ADO Entity Framwork创建一个对象并保存到数据库,如下面的代码所示。
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?
提前致谢。
答案 0 :(得分:13)
一旦调用“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.
}
希望这会有所帮助......