A
A
Anton Ivanov2021-06-13 23:34:03
C++ / C#
Anton Ivanov, 2021-06-13 23:34:03

How to correctly work with child-parent relationships in Entity Framework 6?

there is Parent and Child one-to-one

public class Parent
{
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int? Id { get; set; }

        public Child Child { get; set; }
}

public class Child
{
        [Key, ForeignKey("Parent")]
        public int ParentId { get; set; }
        
        public virtual Parent Parent{ get; set; }
}


if I create a parent object (without saving it to the database yet) and write child to it and save it, then everything is ok.
But at the same time, I cannot work with the child-> parent relation, since there is null

var parent = new Parent();
var child = new Child();

parent.Child = child;

// child.Parent = parent; // Если раскомментировать, будет ошибка: Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values

using (var appDbContext = new AppDbContext()) {
    appDbContext .Parents.AddOrUpdate(parent);
    appDbContext .SaveChanges();
}


if I create a parent, add a child to it and add the same parent (above) to this child, then an error pops up when saving.
It is logical because it turns out parent-> child-> the same parent, which then points to the same child, etc., etc.
(I save it to an absolutely empty database, so there can be no conflicts with any existing entities)

But it is very convenient for me to work with a relationship child.Parentin code.
What is the solution for such a situation?

I see 2 solutions (I don't really like both):
1. Wherever I need to work with parent fields, pass that parent explicitly rather than using the child.Parent. It seems logically it seems that this is how it should be, but I don’t want to rewrite a lot :)
2. Before saving, run through the entire tree of children and clean up the parents (the question is a very simplified example, in reality there are not one or two fields and 4 levels of nesting). But this is quite a crutch already.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question