EF Core composite key gets error while using Fluent Api

So, I have the following class in the Entity Framework Core. I am trying to complete the first migration of code and cannot understand for life how to make a free API for this work.

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

In EF6, I was able to do this in OnModelCreating to make it work fine.

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

But in EF Core I get

"Entity type" Members "has a composite primary key defined with data annotations. To set a composite primary key, use the free API."

I tried using

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

But it just leads to

FOREIGN KEY "FK_Participants_AspNetUsers_ParticipantId" "" . ON DELETE NO ACTION ON UPDATE NO ACTION FOREIGN KEY.

, . , " " EF. "13-full-stack-fundamentals".

UPDATE:

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

" " " , . , API."

2: ,

FOREIGN KEY "FK_Participants_AspNetUsers_ParticipantId" "" . ON DELETE NO ACTION ON UPDATE NO ACTION FOREIGN KEY.

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 needed if anyone knows let me know) 
        modelBuilder.Entity<Participants>()
            .HasOne(p => p.Activity)
            .WithMany()
            .OnDelete(DeleteBehavior.Cascade);
+4
1

, , Activity , EFCore.

, ForeignKey, NavigationProperties , :

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

Source: https://habr.com/ru/post/1676034/


All Articles