简体   繁体   中英

EF Fluent API - Nullable FK for one-to-many on same table

I need to create a nullable foreign key for one-to-many relationship on the same table:

public class NavigationMenu
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public NavigationMenu()
    {
        MenuChildren = new HashSet<NavigationMenu>();
    }

    public string Text { get; set; }
    public string Action { get; set; }
    public string Controller { get; set; }
    public string Icon { get; set; }
    public bool Selected { get; set; }

    public int? NavigationMenuId { get; set; }

    public virtual ICollection<NavigationMenu> MenuChildren { get; set; }

    public virtual NavigationMenu NavigationMenus2 { get; set; }

}

with Fluent Api but i don't know which definition is correct, this:

modelBuilder.Entity<NavigationMenu>()
            .HasOptional(c => c.NavigationMenus2)
            .WithMany(c => c.MenuChildren)
            .HasForeignKey(c => c.NavigationMenuId);

or:

 modelBuilder.Entity<NavigationMenu>()
            .HasMany(e => e.MenuChildren)
            .WithOptional(e => e.NavigationMenus2)
            .HasForeignKey(e => e.NavigationMenuId);

Both are correct, HasMany relationships mean there can be any number of related objects, even 0. (So nullable FK is fine.)

With one-to-one relationships, it needs to be explicitly stated if optional or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM