1:EF

2017-04-18 5 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は最初の子ではnull)。

enter image description here

モデルビルダーコード:

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()に2度電話する必要がありますか?

+0

可能な重複を置き換える(http://stackoverflow.com/questions/ [Entity Frameworkのコードの最初のアプローチで自己の再帰的な関係をマッピングする方法] 12656914/how-to-map-recursive-rel-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; } 
関連する問題