How to remove category without sub category ?
Category Model :
public class Category
{
public virtual int Id{ get; set; }
public virtual string Name { get; set; }
public virtual Category Parent { get; set; }
public virtual int? ParentId { get; set; }
}
datas :
Id ParentId Name
1 null Hot
2 1 Soup
3 1 Coffee
4 3 Decaf Coffee
5 null Cold
6 5 Iced Tea
i need to remove Category with Id=1
but The following error occurs :
The DELETE statement conflicted with the SAME TABLE REFERENCE constraint "FK_dbo.Categories_dbo.Categories_ParentId". The conflict occurred in database "ProjectDatabase", table "dbo.Categories", column 'ParentId'. The statement has been terminated.
my delete code :
public void Delete(int categoryId)
{
var category = _categories.First(d => d.Id == categoryId);
_categories.Remove(category);
}
CategoryConfig :
public class CategoryConfig : EntityTypeConfiguration<Category>
{
public CategoryConfig()
{
ToTable("Categories");
HasOptional(x => x.Parent)
.WithMany()
.HasForeignKey(x => x.ParentId)
.WillCascadeOnDelete(false);
}
}
Well, according to the documentation, if a foreign key on the dependent entity is nullable
, Code First does not set cascade delete on the relationship (which you are doing explicitly), and when the principal is deleted the foreign key will be set to null
.
I don't know why is not doing that in your case, probably is because you are working with an unidirectional relationship and you don't have the collection of children in your parent Category, so EF couldn't set the FK properties to null
in the subcategories, but you can try the following:
var category = _categories.First(d => d.Id == categoryId);
var children=_categories.Where(d=>d.ParentId==categoryId);
foreach(var c in children)
c.ParentId=null;
_categories.Remove(category);