I've got a requirement that I believe must occur very frequently around the world. I have two records that are linked together and whenever a change is made to them a new pair of records is to be created and retain the same link.
The requirement I'm working on has to do with the insurance industry which requires me to deactivate the current insurance policies and re-activate them in a new row in order to show the history of changes made to the insurance policies. When they are re-created they still need to be linked together.
An example of how this process is intended to work from the view of rows in a database:
Insurance Id, Insurance Type, Master Insurance Id, Status
1, Auto Insurance, null, Active
2, Wind Screen Insurance, 1, Active
Note in the above how the link between these policies is denoted by the Master Insurance Id of the second row pointing the the Insurance Id of the first row.
In the code I am writing I am processing each of the policies one at a time so after the first step I have the following:
1, Auto Insurance, null, Inactive
2, Wind Screen Insurance, 1, Active
3, Auto Insurance, null, Active
When I process the second policy I get the following:
1, Auto Insurance, null, Inactive
2, Wind Screen Insurance, 1, Inactive
3, Auto Insurance, null, Active
4, Wind Screen Insurance, 1, Active //needs to be 3 not 1
You'll notice that when I create the new Window Insurance that since we copy the old row we end up with the Master Id insurance pointing to the inactive row.
In order to get around this, I have to keep track of the master insurance id of the previous policy that was processed which has led to the following code:
int masterInsuranceId = -1;
foreach(Policy policy in policyList)
{
//copy the old policy so the new policy has
//the same details as the old one
Policy newPolicy = policyManager.Copy(policy);
//if the new policy is not the master insurance store
//the master its new master insuance
if(newPolicy.MasterInsuranceId.HasValue)
{
newPolicy.MasterInsuranceId = masterInsuranceId;
}
//save the details of the new policy
policyManager.SavePolicy(newPolicy);
//record the master id so we can update the master id
//reference on the next policy
if(newPolicy.MasterInsuranceId == null)
{
masterInsuranceId = newPolicy.Id;
}
else
{
masterInsuranceId = -1;
}
//inactivate the current policy
policy.Status = Inactive;
policyManager.UpdatePolicy(policy);
}
Does anyone know how this can be simplified? What is the best way to ensure two records will remain linked to each other even as a history of the changes is recorded for each change made to the record?