Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Duplicate instances despite EqualityComparison #62

Closed
FBryant87 opened this issue Nov 14, 2017 · 2 comments
Closed

Duplicate instances despite EqualityComparison #62

FBryant87 opened this issue Nov 14, 2017 · 2 comments

Comments

@FBryant87
Copy link

FBryant87 commented Nov 14, 2017

Tried to keep this simple so hopefully it's clear:

DB Forest: I have a Forest which has a Tree in it. There are Sections in my Forest, but these Sections currently have no Trees in them.

Changed Forest: I simply add the Tree object to one of the Sections (there is only one Tree instance still)

This illustrates the small change: https://imgur.com/a/hahD7

I load the DB Forest from the database, and map the Changed Forest to the DB Forest.

I want Entity Framework to automatically detect that a tree has been added to the section, which it does, but it detects it as a newly created tree instance (rather than use the existing object). Thus resulting in duplicate trees.

When I map the objects, I try to tell AutoMapper.Collection to detect this equivalency and not create any new objects, but use the existing ones:

var config = new MapperConfiguration(cfg => {
                cfg.AddCollectionMappers();
                cfg.CreateMap<Forest, Forest>().PreserveReferences().EqualityComparison((s, d) => s.ID == d.ID);
                cfg.CreateMap<Tree, Tree>().PreserveReferences().EqualityComparison((s, d) => s.ID == d.ID);
                cfg.CreateMap<Section, Section>().PreserveReferences().EqualityComparison((s, d) => s.ID == d.ID);
            });
.

The IDs of both trees are identical, but AutoMapper still creates 2 separate tree objects. How might I prevent this? Many thanks.

(EF 6.1.3, AutoMapper 6.0.2, AutoMapper.Collection 3.1.2)

@TylerCarlson1
Copy link
Member

So what I'm seeing is Tree is tied to the Forest and a Section, so there's 2 parent child relationships to Tree. If that's the case AM.Collections can't help because it has no idea about the dual parent relationships. The only way to do this is do an after mapping which corrects the issue, or don't map to sections and pass the matching Forest.Trees object in the DB to the sections, so it doesn't generate a new object.

Also are you using a DTO for your classes? I see it looks like you are cloning here, which might be part of the problem.

@FBryant87
Copy link
Author

Ah so multiple parent relationships are the problem here, many thanks - will close.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants