Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the primary key of an object after it is saved with DbContext

Given this out of context snippet of my code:

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();

Is there a way with Entity Framework to get the primary key that was chosen(seeded) for the calibration object after db.SaveChanges(); completes?

In other words how can I get the primary key for this object after it is committed?

like image 200
Isaiah Nelson Avatar asked Jan 18 '26 18:01

Isaiah Nelson


2 Answers

Reload the entry in the context:

db.Entry(calibration).Reload();

Then you can access the newly created PK

like image 166
Stephen Fischer Avatar answered Jan 20 '26 09:01

Stephen Fischer


Also, You can get from Calibration.PrimaryKeyProperty after db.SaveChanges();

Means,

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;
like image 24
Prasad Kanaparthi Avatar answered Jan 20 '26 09:01

Prasad Kanaparthi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!