あなたは、実際のFKフィールドItemID
とRelativeItemID
表示されません。
public class ItemRelation
{
public long ID { get; set; }
public long ItemID { get; set; } // Missing
[ForeignKey("ItemID")]
[InverseProperty("ItemRelations")]
public virtual Item Item { get; set; }
public long RelativeItemID { get; set; } // Missing
[ForeignKey("RelativeItemID")]
[InverseProperty("RelativeItemRelations")]
public virtual Item RelativeItem { get; set; }
[Required]
public ItemRelationType Type { get; set; }
}
上記宣言はvirtual
ように遅延ロードの動作を使用します。それは必要ではなく、あなたはそれを削除することができます。その結果、怠惰な読み込みはうまくいきません。これは大丈夫です。
public class Item
{
...
public virtual ICollection<ItemRelation> RelativeItemRelations { get; set; }
...
}
そして、あなたのコンテキストクラスには、まだいない場合は、OnModelCreating
をオーバーライドすることにより、カスケード削除規則を無効にする:あなたはプロパティを追加する必要がある第2の関係のためのナビゲーションプロパティをしたいと仮定すると、
次のように:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
...
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
...
このソリューションは、動作するはずですが、効果的カスケードは、多くの関係に、すべて1に削除無効化されます。アップサイドは、流暢なAPIを使用して、ケースバイケースで戻すことができるということです。あなたが望むものを達成するために
第二の方法は、次のようにちょうど流暢なAPIを使用することです:
は、あなたのItem
エンティティに第2のナビゲーションプロパティを追加します。
public class Item
{
...
public virtual ICollection<ItemRelation> RelativeItemRelations { get; set; }
...
}
ItemRelation
エンティティは、FKSが欠落しています、だからここにある:
パブリッククラスItemRelation { public long ID {get;セット; }
public long ItemID { get; set; } // Missing
public virtual Item Item { get; set; }
public long RelativeItemID { get; set; } // Missing
public virtual Item RelativeItem { get; set; }
[Required]
public ItemRelationType Type { get; set; }
}
とナビゲーションプロパティを設定するには、カスケーディングの問題を回避するには、あなただけの流暢APIを使用して関係を定義します。
public TheContext : DbContext
{
public DbSet<Item> Items { get; set; }
public DbSet<ItemRelation> ItemRelations { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ItemRelation>()
.HasRequired(e => e.Item)
.WithMany(t => t.ItemRelations)
.HasForeignKey(e => e.ItemID)
.WillCascadeOnDelete(false);
modelBuilder.Entity<ItemRelation>()
.HasRequired(e => e.RelatedItem)
.WithMany(t => t.RelativeItemRelations)
.HasForeignKey(e => e.RelativeItemID)
.WillCascadeOnDelete(false);
// Uncomment the following if you want to disable all cascading deletes and automatic fk creation conventions
// modelBuilder.Conventions.Remove<ForeignKeyIndexConvention>();
// modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
// modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
...
}
}
Read here for an opinion on why you might consider disabling those conventions.
「いくつかの言語辞書モデル」、「いくつかの「関係」、「何らかの誤り」、「1つの場合 - 他の場合」 - これはすべてあいまいです。 –