本文介绍了一对多关系仅在一侧具有导航属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两个表之间有很好的一对多关系: Play Player :

I have perfectly fine one-to-many relationship between two tables: Play and Player:

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 集合?

Is it possible to omit navigation property on side? For example remove Plays collection from Player?

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

我要问两个具体问题:

  1. 有可能做到吗?
  2. 是否有可能做到这一点而无需依赖EF Core约定-例如"Id"是主键,等等?(意味着,将所有内容显式化,以流利的API或注释形式显示)

推荐答案

绝对有可能.编写您的实体配置,如下所示:

Absolutely possible. Write you entity configuration as follows:

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

不!没有 Fluent API ,这是不可能的.

No! Its not possible without Fluent API.

这篇关于一对多关系仅在一侧具有导航属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:08