MG123
MG123

Reputation: 492

EF Core ForeignKey attribute - how to make it nullable

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)?

Upvotes: 2

Views: 4624

Answers (2)

Lee
Lee

Reputation: 763

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

Upvotes: 0

BerkGarip
BerkGarip

Reputation: 544

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.

Upvotes: 0

Related Questions