'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)?
Solution 1:[1]
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.
Solution 2:[2]
You can use the modelbuilder
mb.Entity<MenuItem>
.HasOne(o1 => o1.Parent)
.WithOne(o2 => o2.MenuItem)
.IsRequired(false);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BerkGarip |
| Solution 2 | Lee |
