使用 Fluent Api 时复合键 EF Core 出错

Composite Key EF Core getting error when using Fluent Api

所以我在 Entity Framework 核心中有以下 class。我正在尝试进行代码优先迁移,但我终其一生都无法弄清楚如何使这项工作变得流畅 API。

public class Participants
{
    public Activity Activity { get; set; } //Class with Id and Name of Activity
    public ApplicationUser Participant { get; set; } 

    [Key]
    [Column(Order = 1)]
    public int ActivityId { get; set; }


    [Key]
    [Column(Order = 2)]
    public string ParticipantId { get; set; }
}

在 EF6 中,我能够在 OnModelCreating 中执行此操作以使其正常工作。

 modelBuilder.Entity<Attendance>()
            .HasRequired(a => a.Activity)
            .WithMany()
            .WillCascadeOnDelete(false);

但在 EF Core 中我得到

" Entity type 'Participants' has composite primary key defined with data annotations. To set composite primary key, use fluent API."

我试过使用

modelBuilder.Entity<Participants>().HasKey(p => new {p.Activity, p.Participant});

但是,这只会导致

Introducing FOREIGN KEY constraint 'FK_Participants_AspNetUsers_ParticipantId' on table 'Participants' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

如果有更好的方法来完成整个事情,我愿意接受建议。如果您有 pluralsight 订阅,我基本上是在尝试让 Mosh Hamedani 的 "Become a Full Stack Developer" 在 EF 核心中工作。该示例位于“13-full-stack-fundamentals”文件夹中。

更新:也尝试过

        modelBuilder.Entity<Participants>()
            .HasOne(p => p.Activity)
            .WithMany()
            .OnDelete(DeleteBehavior.Cascade);

还有

"Entity type 'Participants' has composite primary key defined with data annotations. To set composite primary key, use fluent API."

更新 2:在尝试了 Roy 的建议后,这就是我得到的结果

Introducing FOREIGN KEY constraint 'FK_Participants_AspNetUsers_ParticipantId' on table 'Participants' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

更新 3:在迁移中

我删除了其中一个 OneDelete: ReferntialAction.Cascade 并且它起作用了。我删除了 FK_Participants_AspNetUsers_ParticipantId.

中的一个

我在 OnModelCreating 中也改成了这个

        modelBuilder.Entity<Participants>()
            .HasKey(p => new { p.ActivityId, p.ParticipantId });
        base.OnModelCreating(modelBuilder);

        //Added this ( Not sure if it's needed if anyone knows let me know) 
        modelBuilder.Entity<Participants>()
            .HasOne(p => p.Activity)
            .WithMany()
            .OnDelete(DeleteBehavior.Cascade);

您要做的是在 Activity 和 Participant 之间建立关系,这在 EFCore 中有点不同。

为此,您需要在模型构建器中引用 ForeignKey Properties 而不是 NavigationProperties,如下所示:

    modelBuilder.Entity<Participants>()
        .HasKey(p => new { p.ActivityId , p.ParticipantId });