I have some code that's adding new child records ("installment dates") of a parent record to my DbContext
. I've just noticed that after I add one to the set, the parent's InstallmentDates
collection (a navigation property) is not updated to contain the new object. This is what I was expecting. But after adding the next one, the InstallmentDates
property updates and contains the first one added.
List<PayPlanInstallmentDate> installmentDates = new List<PayPlanInstallmentDates>();
foreach (var installmentDateSpec in payPlanSpec.InstallmentDates)
{
var dbInstallmentDate = CRMEntity<PayPlanInstallmentDate>.GetOrCreate(installmentDateSpec.ID);
if (dbInstallmentDate.ID == Guid.Empty) dbInstallmentDate.ID = Guid.NewGuid();
dbInstallmentDate.fk_PayPlanID = dbPayPlan.ID;
dbInstallmentDate.InstallmentNumber = installmentDateSpec.InstallmentNumber;
dbInstallmentDate.DueDate = installmentDateSpec.DueDate;
installmentDates.Add(dbInstallmentDate);
}
Where CRMEntity<PayPlanInstallmentDate>.GetOrCreate
ultimately calls:
public virtual T AddNew(T newEntity)
{
return DBContext.Set<T>().Add(newEntity);
}
I can see why this might happen since when I Add
the new entity, it isn't yet associated by the foreign key. However, the result is that dbPayPlan.PayPlanInstallmentDates
is left with all but the last one added. I would be fine with it containing none of the new records or all of them, but all but one could be problematic. Is there a way to make it refresh again without Add
ing something?