Saving an EF Instance with Multiple Parents

When mapping back from business logic objects to EF objects, one of the main problems that I am having is when the same instance has 2 parents:

enter image description here

(Objects are yellow, properties are orange)

In the world of business logic, there is only one instance of the Tree object (which appears as a child of several parents: a forest and a partition)

When I rewrite everything back to EF objects using AutoMapper, EF assumes that there are two separate tree instances (even though they have the same identifier). Therefore, it creates a duplicate in the database.

What is the correct way to manage this scenario so that both forests and partitions point to the same tree record in the database?

, , ?

+4
2

Unfortunatelly EF Tree, Forest ( ), , Automapper .

Automapper , :

var config = new MapperConfiguration(cfg =>
{
   cfg.CreateMap<Tree, TreeEF>().PreserveReferences();
});

- Forest Section Tree, .

class Program
{
    static void Main(string[] args)
    {
        var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Forest, ForestEF>().PreserveReferences();
                cfg.CreateMap<Section, SectionEF>().PreserveReferences();
                cfg.CreateMap<Tree, TreeEF>().PreserveReferences();
            });

        var mapper = config.CreateMapper();

        var forest = new Forest();
        var section = new Section();
        var tree = new Tree();

        forest.Trees.Add(tree);
        forest.Sections.Add(section);
        section.Trees.Add(tree);

        var result = mapper.Map<Forest, ForestEF>(forest);

        Console.WriteLine(object.ReferenceEquals(result.Trees[0], result.Sections[0].Trees[0]));
        Console.ReadLine();
    }
}

public class Forest
{
    public IList<Tree> Trees { get; set; } = new List<Tree>();
    public IList<Section> Sections { get; set; } = new List<Section>();
}

public class Section
{
    public IList<Tree> Trees { get; set; } = new List<Tree>();
}

public class Tree
{
}

public class ForestEF
{
    public IList<TreeEF> Trees { get; set; } = new List<TreeEF>();
    public IList<SectionEF> Sections { get; set; } = new List<SectionEF>();
}

public class SectionEF
{
    public IList<TreeEF> Trees { get; set; } = new List<TreeEF>();
}

public class TreeEF
{
}
+2

, , ID, , EF , ( ). , . GUID, , , , .

+1

Source: https://habr.com/ru/post/1689447/


All Articles