How NOT to cascade delete records with 1-n relationship using Entity Framework?

Asked

Viewed 138 times

2

I have a table Menu that may have many Categories and these Categories may have only one Menu:

public class Menu
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Menu Menu { get; set; }
}

I want to be able to delete one Menu without having to delete the Categories related. What options do I have to solve this problem?

1 answer

1


Making foreign key optional.

Modify Category to the following:

public class Category
{
    public int Id { get; set; }
    public int? MenuId { get; set; }

    public string Name { get; set; }
    public virtual Menu Menu { get; set; }
}

The other thing to do is to force the cascadeDelete as false in Migration:

    CreateTable(
            "dbo.Menu",
            c => new
                {
                    ...
                })
            .PrimaryKey(t => t.MenuId)
            .ForeignKey("dbo.Categories", t => t.MenuId, cascadeDelete: false)
            .Index(t => t.MenuId);

When deleting a menu, category items will be orphaned (MenuId receives null).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.