0

I’m trying to copy/clone entity graph with EF6.1 and getting duplicate entities.

Below is a piece of my model which consist of a Template that I want to modify, copy and assign to different users, something like Save As function.

Here is my entities model:

Model

What I’m doing is:

var newTemplate = ctx.Templates
.Where(t => t.TemplateId == SelectedTemplate.TemplateId)
.Include(t => t.Properties.Select(p => p.PropertyCollections))
.Include(t => t.Properties.Select(p => p.Values))
.AsNoTracking()
.First();
newTemplate.TemplateName = newTemplateName;
ctx.Templates.Add(newTemplate);
ctx.SaveChanges();

And what I get is shown below where “Template1” is the source and “Template2” is the copy in which every ‘PropertyCollection’ has a duplicated entry for each ‘Property’.

Result after copy:

enter image description here

I understood that with AsNoTracking there is no identity mapping which is the reason behind this but I can’t find even a custom solution.

Damian Kozlak
  • 7,065
  • 10
  • 45
  • 51
  • I think by doing the AsNoTracking it has assumed none of the objects already exist and so creates new entries. This is just an opinion I'm making with out actually having used it before. – Oliver Nov 12 '15 at 12:20

2 Answers2

0

I didn't really test your code, but I think your Entities might really get messed up when doing it that way. Maybe this attempt would work for you. It's for EF4 but might work.

Community
  • 1
  • 1
thmshd
  • 5,729
  • 3
  • 39
  • 67
0

You are adding the whole graph, so EF is inserting everything. You are using AsNoTracking to "trick" EF instead of its original purpose.

I would suggest you to write a few lines of code to actually implement your business requirement, which is create a new Template based on another one.

So, get the template (without the AsNoTracking), and create a new template initializing the properties based on the original template values. Then add the new template to the context. EF will insert the new template and reference the existing dependent entities.

This is also a safer way to implement this, as in the future you might require to set some properties with different values in the new template.

Francesc Castells
  • 2,692
  • 21
  • 25