Copy/clone of Entity Framework with many-to-many relationship

dbcontext entity-framework entity-framework-6

Popular Answer

So, I made the "brute force" decision shown below. I'm still baffled by the mechanics behind why I'm unable to change the funds. GoalId is used in the loop that develops new goals. GoalId. Not all ignorance is bliss.

Here is the answer.

// Keep track of the mapping of old goals to new goals
Dictionary<Guid, Guid> oldGoalId = new Dictionary<Guid, Guid>();

var detachedPlan = db.Plans
  .FirstOrDefault(p => p.PlanId == originalPlan.PlanId);

foreach (var goal in detachedPlan.Goals.ToList())
  Guid newGoalId = Guid.NewGuid();
  oldGoalId.Add(goal.GoalId, newGoalId); // record old and new goalId for the new goal

  // BTW, this seems like the right solution, but it's not.
  // This loop creates unwanted additional copies of the funding in the old Plan
  // foreach (Funding funding in goal.Fundings.ToList())
  //    funding.GoalId = newGoalId;
  goal.GoalId = newGoalId;

foreach (var account in detachedPlan.Accounts.ToList())
  account.AccountId = Guid.NewGuid();
  foreach (var contributionStream in account.ContributionStreams.ToList())
    Guid newContributionStreamId = Guid.NewGuid();
    var fundingList = contributionStream.Fundings.ToList();
    contributionStream.ContributionStreamId = newContributionStreamId;
    foreach (Funding funding in fundingList)
      funding.ContributionStreamId = newContributionStreamId;
      // update the GoalId here.
      // Not sure why it can't be updated in the commented out loop above
      funding.GoalId = oldGoalId[funding.GoalId];
      funding.FundingId = Guid.NewGuid();
detachedPlan.PlanId = Guid.NewGuid();
detachedPlan.Name += " copy";
8/18/2018 3:25:41 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow