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

2

I have a table Menu which can have many Categories and these Categories can only have a 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 a Menu without having to delete the Categories related. What options do I have to resolve this problem?

    
asked by anonymous 20.08.2015 / 20:07

1 answer

1

Making the foreign key optional.

Change 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 cascadeDelete as false on 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, the category items will be orphaned ( MenuId receive null ).

    
20.08.2015 / 20:12