你缺少实际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.
“一些语言词典模型”,“一些关系“,”一些错误“,”一个案例 - 另一个案例“ - 这些都很模糊。 –