EF Core ForeignKey attribute - how to make it nullable

1.6k Views Asked by At

I'm using EF Core to create a "MenuItem" table, which may be linked to a parent (of "MenuItem") like so ...

public class MenuItem
{
    public int MenuItemId { get; set; }

    [ForeignKey("ParentMenuItemId")]
    public virtual MenuItem Parent { get; set; }
}

ParentMenuItemId gets created as NOT NULL - how can I define it so Parent may be null (for root level MenuItem records)?

2

There are 2 best solutions below

1
BerkGarip On

well, it's easy. all you have to do is this putting a ? after defining type of object like this:

public class MenuItem
{
    public int? MenuItemId { get; set; }

    [ForeignKey("ParentMenuItemId")]
    public virtual MenuItem Parent { get; set; }
}

but, you need to make sure there is a no such as [Required] tags on that relation object.

0
Lee On

You can use the modelbuilder

mb.Entity<MenuItem> 
        .HasOne(o1 => o1.Parent)  
        .WithOne(o2 => o2.MenuItem)
        .IsRequired(false);  

https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-composite-key%2Csimple-key#manual-configuration