【发布时间】:2016-10-22 12:25:35
【问题描述】:
我正在开发一个 ASP.NET MVC 项目。我正在使用实体框架代码优先方法与数据库进行交互。但是我在为实体的自引用外键设置级联删除时遇到问题。
这是我的带有自引用外键的实体类
public class Category
{
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[MaxLength(55)]
public string MmName { get; set; }
public int? ParentId { get; set; }
[ForeignKey("ParentId")]
public virtual Category ParentCategory { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
这是我的上下文
public class StoreContext : DbContext
{
public StoreContext():base("DefaultConnection")
{
}
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Category>().HasOptional(x => x.ParentCategory).WithMany(c => c.Categories).WillCascadeOnDelete();
}
}
当我运行时,抛出多个级联路径错误
Introducing FOREIGN KEY constraint 'FK_dbo.Categories_dbo.Categories_ParentId' on table 'Categories' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint. See previous errors.
是否可以先在实体框架代码中为自引用外键设置删除级联?
【问题讨论】:
标签: asp.net entity-framework ef-code-first foreign-keys entity-framework-migrations