【问题标题】:EF Fluent API - Nullable FK for one-to-many on same tableEF Fluent API - 同一张表上一对多的可空 FK
【发布时间】:2017-01-24 15:34:13
【问题描述】:

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

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

}

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

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

或:

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

【问题讨论】:

  • 两者都是正确的。

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


【解决方案1】:

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

对于一对一的关系,需要明确说明是否可选。

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 2013-03-15
    • 2012-09-22
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多