Assign EF Core identity id to a property after an insert in the database has been made?

689 Views Asked by At

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?

1

There are 1 best solutions below

0
TroyB On

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.

private class TrainingPlan
{
public Guid ResourceID
public string Name
}

trainingPlan.ResourceID = Guid.NewGuid();
trainingPlan.subObject.parentTrainingPlan = trainingPlan.ResourceID
await dbcontext.SaveChangesAsync();