我有以下类,并且我使用EF Code-first创建了数据库表。但是,我发现删除级联已启用并尝试将其删除。
public class Category
{
[Key, DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[MaxLength(100)]
public string Title { get; set; }
public virtual ICollection<Event> Events { get; set; }
}
public class Event
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[ForeignKey("Category")]
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
}
我在DbContext类中添加了以下代码。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Use singular table names
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
Database.SetInitializer<MyContext>(null);
modelBuilder.Entity<Category>()
.HasMany(c => c.Events)
.WithRequired()
.HasForeignKey(e => e.CategoryId)
.WillCascadeOnDelete(false);
}
但是,生成的迁移代码会生成两个AddForeignKey
状态,其中一个状态为cascadeDeletion,另一个状态为没有状态。
AddForeignKey("dbo.Event", "CategoryId", "dbo.Category", "Id");
AddForeignKey("dbo.Event", "CategoryId", "dbo.Category", "Id", cascadeDelete: true);
CreateIndex("dbo.Event", "CategoryId");
CreateIndex("dbo.Event", "CategoryId");
答案 0 :(得分:0)
您使用的.WithRequired()
来电configures the relationship to be optional:required without a navigation property on the other side of the relationship,这样就可以进行一次AddForeignKey
来电。
然后您有一个Category
导航属性尚未在FluentAPI中配置,因此EF会生成另一个使用默认配置的AddForeignKey
调用。
尝试使用WithRequired
modelBuilder.Entity<Category>()
.HasMany(c => c.Events)
.WithRequired(e => e.Category)
.HasForeignKey(e => e.CategoryId)
.WillCascadeOnDelete(false);
覆盖
{{1}}