[英]Entity Framework POCO - Possible to set Cascade?
I have your basic recursive categories that are linked between each other. 我有彼此链接的基本递归类别。 When I try to delete a category that has children I get your usual error.
当我尝试删除有孩子的类别时,出现通常的错误。
What I always did is made a functions to recursively delete all children but I wonder can I just somehow set CASCADE ON DELETE somehow to my POCO class that is using EF so I would not need implement my own deletion mechanics? 我一直做的工作是递归删除所有子级的函数,但是我不知道我是否可以以某种方式将CASCADE ON DELETE设置为使用EF的POCO类,这样就不需要实现自己的删除机制了?
The DELETE statement conflicted with the SAME TABLE REFERENCE constraint "FK_dbo.Categories_dbo.Categories_RootCategoryId".
DELETE语句与SAME TABLE REFERENCE约束“ FK_dbo.Categories_dbo.Categories_RootCategoryId”冲突。 The conflict occurred in database "Website", table "dbo.Categories", column 'RootCategoryId'.
在数据库“网站”的表“ dbo.Categories”的列“ RootCategoryId”中发生了冲突。
public class Category
{
public int Id { get; set; }
public int? RootCategoryId { get; set; }
public virtual Category RootCategory { get; set; }
public virtual ICollection<Category> ChildCategories { get; set; }
}
Currently I delete relation before deleting a category. 目前,我在删除类别之前先删除关系。 But what if I want to delete all child-categories recursively?
但是,如果我想递归删除所有子类别怎么办? Only cascading them will accomplish that.
只有级联他们才能达到目的。
public ActionResult Delete(int id)
{
var category = _db.Categories.Single(x => x.Id == id);
if (category.RootCategoryId == null)
{
category.ChildCategories.ToList().ForEach(x => x.RootCategoryId = null);
}
else
{
category.ChildCategories.ToList().ForEach(x => x.RootCategoryId = category.RootCategoryId);
}
_db.Categories.Remove(category);
_db.SaveChanges();
return RedirectToAction("Index", "Category");
}
The way I would approach this issue would be to use the OnModelCreating Fluent api. 我要解决此问题的方法是使用OnModelCreating Fluent API。
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasMany(u => u.ProjectAuthorizations)
.WithRequired(a => a.UserProfile)
.WillCascadeOnDelete(true);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.