简体   繁体   中英

Insert record in database from template record without altering template - Entity Framework

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.Models is 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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM