The entity type 'MigrationOperation' requires a primary key to be defined

.net-core asp.net c# entity-framework-core

Question

I am trying to build my first .NET app using Identity. It will be a basic Workout app, but I have been having trouble figuring out the Keys and ForeignKeys within Identity. Here is my ExerciseController:

 using System.Collections.Generic;
 using System.ComponentModel.DataAnnotations;
 using System.ComponentModel.DataAnnotations.Schema;
 using WorkoutGenerator.Data.Migrations;

    namespace RandomWorkout.Models
    {
    public class Exercise
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public MuscleGroup MuscleGroup { get; set; }
        public int MuscleGroupID { get; set; }
        [Key]
        public int ID { get; set; }

        [ForeignKey("ID")]
        public virtual ApplicationUser User { get; set; }

        public IList<ExerciseWorkout> ExerciseWorkouts { get; set; } = new List<ExerciseWorkout>();
    }

}`

When I run the migration however, I get the error

They entity type 'MigrationOperation' requires a primary key to be defined.

I have run into this issue with other entities, in which case I just had to make a new builder.Entity in my DbContext class. With the MigrationOperation however, this doesn't seem to be the case. Am I completely on the wrong track of how to JOIN my table with the auto generated User table? Thanks

1
1
3/6/2018 3:16:29 PM

Accepted Answer

Try this:

public class Exercise {
    public string Name { get; set; } 
    public string Description { get; set; } 
    public MuscleGroup MuscleGroup { get; set; }
    public int MuscleGroupID { get; set; } 

    [Key] 
    public int Id { get; set; } 

    public int UserId {get; set;}
    [ForeignKey("UserId")] 
    public virtual ApplicationUser User { get; set; } 

    public IList<ExerciseWorkout> ExerciseWorkouts { get; set; } = new List<ExerciseWorkout>(); 
 }

Add a int for foreignkey and define an id property for primary key

1
3/6/2018 5:49:13 AM

Popular Answer

for solved this problem It's better define id private the get by your Id

private Guid _id;
[Key]
public Guid ID
{
get { return _id; }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow