0

I have the following two entities:

public class Project
{
    [Required]
    public int ProjectId { get; set; }

    [Required]
    public string Name { get; set; }

    public virtual HashSet<Level> Structure { get; set; } = new HashSet<Level>();

}

public class Level
{
    [Required]
    public int LevelId { get; set; }

    [Required]
    public int ProjectId { get; set; }

    public int? ParentLevelId { get; set; }

    public virtual Project Project { get; set; }

    public virtual HashSet<Level> Children { get; set; } = new HashSet<Level>();
}

A project has one or more Levels, and each level (or sublevel) can have several children.
Level.ParentLevelId is NULL for top-most levels, while for children it is filled with the parents' Id.
Level.ProjectId is always filled, even for children, because we need it for faster filtering.

Now I am having trouble inserting new Projects into the DB when calling _context.Projects.AddAsync(projectEntity) (where projectEntity is the Project with the entire structure).

Before, Level.ProjectId was nullable because we did not need it on the children. This worked fine, as EF was adding the ProjectId for top-most levels due to the navigation property Project.Structure. In the same way, the childrens Level.ParentLevelId was correctly filled thanks to the navigation property Level.Children.

Now that Level.ProjectId is required for children, though, inserts are not working anymore. The field is correctly filled for top-most Levels, as it was before, but of course not for children since they are not connected directly to the project but just to the parent level.

Is there any way of solving this, maybe by propagating the ID or using some more navigation properties? Or do I really need to split it into multiple queries?

Davide De Santis
  • 922
  • 1
  • 10
  • 25

0 Answers0