1:EF

2017-04-18 31 views
1

1自我的关系我有型ScheduleItem1:EF

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; } 

} 

的对象时,此对象是父对象,它里面有孩子的集合。

每个孩子都有对下一个孩子的可选引用(最后一个孩子将拥有NextDestinationId = null)和对前一孩子的可选引用(对于第一个孩子,PreviousDestinationId应该为空)。

enter image description here

型号Builder代码:

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

然而,当保存我得到这个错误 无法确定相关的操作有效的排序。由于外键约束,模型要求或商店生成的值,可能会存在依存关系。

这个问题的解决方案是什么?我必须拨打SaveChanges()两次吗?

+0

的可能的复制[如何映射实体框架代码优先方法自我递推关系](http://stackoverflow.com/questions/ 12656914/how-to-map-recursive-relation-on-self-in-entity-framework-code-first-approach)@OP:勾选这个答案。 Imho,这是一个完美的解决方案 –

回答

2

解决方案是重新考虑关系和结构。我没有评论父母/子女关系,因为你没有解释为什么同一类型的父母(递归关系)是必要的。

兄弟姐妹关系不是必需的,将它们全部删除并用SortOrder数字类型列替换。父母应该根据这种类型返回一个排序列表/集合。时间表项目不应该知道与它们相邻的下一个/上一个时间表项目,让父母担心这一点。

所以更换

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

// sort from low-to-high in the context of a collection 
public int SortOrder { get; set; }