0

I am trying to insert a record into my database based on an existing record which functions as template using Entity Framework.

The flow right now is:

var newModel = organization.Models.Where(m => m.IsTemplate == true).FirstOrDefault();

newModel.Name = "Something New";
newModel.IsTemplate = false;

organization.Models.Add(newModel);
_organizationRepo.SaveChanges();

Note that organization.Modelsis read from the repository beforehand.

My problem is that instead of creating a dublicate record with the new name and no tempalte flag, the template record is altered.

Criteria:

  • I want to create a new record which is a copy of an existing record
  • I want to alter the new record
  • I do NOT want to alter the existing record

I would assume Entity Framework would interpret the organization.Models.Add(newModel) statement as insert new record but it does not.

M. Larsen
  • 27
  • 7

1 Answers1

0

The solution to the problem was (as Arie commented on the original question) to use AsNoTracking() as described here when finding the template entry.

One catch using this is that this workaround is not meant as

"read values (template) -> Change as needed -> insert new record"

but rather a read-only operation. This meant that I had to manually eager load all references to the template in order to ensure these getting included in the Add() operation on the DataContext.

I did this by loading properties into a variable before saving the object eg.

var modelFromTemplate = organization.Models.FirstOrDefault(m => m.IsTemplate == true);
var eagerLoadParams = modelFromTemplate.Parameters.ToList();

//Change stuff as needed on the template here
modelFromTemplate.Name = "Something New";
modelFromTemplate.IsTemplate = false;

//Save the new model
_modelRepo.Add(modelFromTemplate);
_modelRepo.SaveChanges();
Community
  • 1
  • 1
M. Larsen
  • 27
  • 7