EF Fluent API - Nullable FK,用于同一桌上的一对多

时间:2017-01-24 15:34:13

标签: c# entity-framework one-to-many foreign-key-relationship ef-fluent-api

我需要在同一个表上为一对多关系创建一个可以为空的外键:

C:\My Scripts>test.bat
Time-Now: 9:29
Time-Out: 4:45
Press any key to continue . . .
Time-Out: ECHO is on.:
Press any key to continue . . .
1 was unexpected at this time.

使用Fluent Api,但我不知道哪个定义是正确的,这个:

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; }

}

或:

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

1 个答案:

答案 0 :(得分:1)

两者都是正确的,HasMany关系意味着可以有任意数量的相关对象,甚至0。 (所以可以为空的FK很好。)

如果是一对一关系,则需要明确说明是否可选。