你缺少實際FK領域ItemID
和RelativeItemID
:
,並配置您可以使用InverseProperty
屬性,以禁用位EF公約沿導航性能(如下圖所示)。
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
刪除慣例,如果您還沒有,在你的上下文類如下:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
...
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
...
這個解決方案應該工作,但它是有效地禁用級聯刪除所有一對多的關係。好處在於,您可以通過使用流暢的API逐案獲取它。
達到你想要的是隻使用流暢API如下第二種方法:
第二導航屬性添加到您的Item
實體:
public class Item
{
...
public virtual ICollection<ItemRelation> RelativeItemRelations { get; set; }
...
}
ItemRelation
實體缺少FKS,所以這裏是:
public class ItemRelation { public long ID {get;組; }用流利的API
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; }
}
並配置導航屬性,避免級聯問題,你剛纔定義的關係:
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.
「一些語言詞典模型」,「一些關係「,」一些錯誤「,」一個案例 - 另一個案例「 - 這些都很模糊。 –