I have this method:
public async Task<TrainingPlan> CreateTrainingPlan(TrainingPlanDTO trainingPlan)
{
TrainingPlan tp = new TrainingPlan
{
Name = trainingPlan.Name
};
// adding to context
_context.TrainingPlan.Add(tp);
// assign database identity id to property
trainingPlan.ResourceId = tp.Id;
// more entities being saved in dbcontext
// final save in database
await dbcontext.SaveChangesAsync();
}
What I would want is to assign the identity id of the entity inserted after the insert in the database itself was done in order to not do multiple calls to the database. I have tested the method and trainingPlan.ResourceId is always 0 as it takes the initial value of tp.Id, not the new one that is assigned after the SaveChangesAsync method has been called.
I would need to hold a reference to the tp.Id. Is it possible to user ref keyword in this case?
Another option is to use a manually generated primary key - perhaps a guid, instead of using an automatically generated integer value. Then you can assign the new guid to whatever object(s) you are creating before saving the data to the database. You would also need to change the type of your primary key object and related object keys to match whatever primary key type you want to use.