如何在使用DbContext保存对象后获取对象的主键

时间:2013-04-05 18:53:51

标签: c# entity-framework entity-framework-5

鉴于我的代码的上下文片段:

var calibration = new Calibration
{
    CalibrationType = SelectedTest.TestTypeId
    ,Expiration = expirationDate
    ,LastSaved = DateTime.Now
    ,StatusTypeId = 1
    ,TechnicianId = SelectedTechnician.Id
    ,Phases = BuildCalibrationPhases()
};

db.Calibrations.Add(calibration);
db.SaveChanges();

db.SaveChanges();完成后,实体框架是否有办法获取校准对象所选的主键(种子)?

换句话说,如何提交此对象后的主键?

2 个答案:

答案 0 :(得分:4)

在上下文中重新加载条目:

db.Entry(calibration).Reload();

然后您可以访问新创建的PK

答案 1 :(得分:2)

此外,您可以在db.SaveChanges();

之后从Calibration.PrimaryKeyProperty获取

手段,

var calibration = new Calibration
{
    CalibrationType = SelectedTest.TestTypeId
    ,Expiration = expirationDate
    ,LastSaved = DateTime.Now
    ,StatusTypeId = 1
    ,TechnicianId = SelectedTechnician.Id
    ,Phases = BuildCalibrationPhases()
};

db.Calibrations.Add(calibration);
db.SaveChanges();



int value = Calibration.PrimaryKeyProperty;