EF Fluent API - 一对多的可空 FK table
EF Fluent API - Nullable FK for one-to-many on same table
我需要在同一个 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; }
}
使用 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);
两者都是正确的,HasMany关系意味着可以有任意数量的相关对象,甚至0。
(因此可为空的 FK 很好。)
有one-to-one关系,是否可选需要明确说明。
我需要在同一个 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; }
}
使用 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);
两者都是正确的,HasMany关系意味着可以有任意数量的相关对象,甚至0。 (因此可为空的 FK 很好。)
有one-to-one关系,是否可选需要明确说明。