1

I have a object of type ScheduleItem

 public class ScheduleItem : EntityBase
    {
        [MaxLength(500)]
        [Required]
        public string TitleAr { get; set; }

        [MaxLength(300)]
        [Required]
        public string TitleEn { get; set; }
        public int? ParentScheduleItemId { get; set; }


        public int? PreviousDestinationId { get; set; }
        public int? NextDestinationId { get; set; }

        public ScheduleItem ParentScheduleItem { get; set; }

        [InverseProperty("ParentScheduleItem")]
        public ICollection<ScheduleItem> ChildrenScheduleItems { set; get; }

        public ScheduleItem PreviousDestination { get; set; }
        public ScheduleItem NextDestination { get; set; }

}

This object is the parent object, inside it there's a collection of children.

Each child has an optional reference to the next child (the last child will have NextDestinationId = null) and an optional reference to the previous child (PreviousDestinationId should be null for the first child).

enter image description here

Model Builder code:

   modelBuilder.Entity<ScheduleItem>().HasOptional(t => t.NextDestination).WithMany().HasForeignKey(t => t.NextDestinationId);
        modelBuilder.Entity<ScheduleItem>().HasOptional(t => t.PreviousDestination).WithMany().HasForeignKey(t => t.PreviousDestinationId);

However, when saving I get this error unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.

What's the solution to this problem? do I have to call SaveChanges() twice?

Ra'ed Alaraj
  • 173
  • 1
  • 15
  • Possible duplicate of [How to map recursive relation on self in Entity Framework code-first approach](http://stackoverflow.com/questions/12656914/how-to-map-recursive-relation-on-self-in-entity-framework-code-first-approach) @OP: check this answer. Imho, this is the perfect solution – Matthias Burger Apr 18 '17 at 09:56

1 Answers1

2

The solution is to rethink the relationship and structure. I have no comment on the parent/child relationship as you do not explain why a parent of the same type (a recursive relationship) is necessary.

The sibling relationship is not necessary, remove that all together and replace it with a SortOrder column of numeric type. The parent should then return a sorted list/collection based on this type. The schedule items should not have to know about the next/previous schedule items that are adjacent to them, let the parent worry about that.

So replace

public int? PreviousDestinationId { get; set; }
public int? NextDestinationId { get; set; }
public ScheduleItem PreviousDestination { get; set; }
public ScheduleItem NextDestination { get; set; }

with

// sort from low-to-high in the context of a collection
public int SortOrder { get; set; }
Igor
  • 60,821
  • 10
  • 100
  • 175