【问题标题】:One-To-Many relationship with navigation property only on one side?仅在一侧与导航属性的一对多关系?
【发布时间】:2020-02-20 11:07:27
【问题描述】:

我在两个表之间有完美的一对多关系:PlayPlayer

public class Player
{
    public int PlayerId { get; set; }
    public string Name { get; set; }

    public ICollection<Play> Plays { get; set; }
}

public class Play
{
    public int PlayId { get; set; }

    public int PlayerId { get; set; }
    public Player Player { get; set; }
}

modelBuilder.Entity<Play>()
    .HasOne<Player>(p => p.Player)
    .WithMany(p => p.Plays)
    .OnDelete(DeleteBehavior.Cascade)
    .HasForeignKey(p => p.PlayerId)
    .IsRequired();

是否可以在侧面省略导航属性?例如从Player 中删除Plays 集合?

public class Player
{
    public int PlayerId { get; set; }
    public string Name { get; set; }
}

我要问两个具体问题:

  1. 有可能做到吗?
  2. 是否可以在不依赖 EF Core 约定的情况下做到这一点 - 例如“Id”是主键等...? (意思是让一切都明确,无论是在流畅的 API 中还是作为注释)

【问题讨论】:

  • 我知道 EF Core 有一些约定,这样您就不必在 fluent API 中编写任何代码。就像属性 Id 一样,EFCore 将创建 PK,无需注释或 FluentAPI。我不想得到类似“您不必这样做,因为 EFCore 将使用其约定自动解释这一点”这样的答案
  • @TanvirArjel 但看起来你的答案就是我要找的答案。谢谢

标签: c# entity-framework .net-core entity-framework-core ef-fluent-api


【解决方案1】:

是否可以在侧面省略导航属性?例如从Player 中删除Plays 集合?

绝对有可能。编写你的实体配置如下:

modelBuilder.Entity<Play>()
    .HasOne<Player>(p => p.Player)
    .WithMany() // <-- Here it is
    .HasForeignKey(p => p.PlayerId)
    .OnDelete(DeleteBehavior.Cascade)
    .IsRequired();

是否可以在不依赖 EF Core 约定的情况下做到这一点 - 例如“Id”是主键等...? (意思是让一切都明确,无论是在流畅的 API 中还是作为注释)

不!没有 Fluent API 是不可能的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-18
    相关资源
    最近更新 更多