i am working on a project in C# (.NET), and i want to make initial migration but i got a problem. i have tried so many solutions but still got error.
AppDBContext:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
object value = modelBuilder.Entity<Actor_Movie>().HasKey(am => new
{
am.ActorId,
am.MovieId,
}
);
modelBuilder.Entity<Actor_Movie>().HasOne(m => m.Movie).WithMany(am => am.Actors_Movies).HasForeignKey(m => m.MovieId);
modelBuilder.Entity<Actor_Movie>().HasOne(m => m.Actor).WithMany(am => am.Actors_Movies).HasForeignKey(m => m.ActorId);
base.OnModelCreating(modelBuilder);
}
MovieCategory.cs:
namespace eTickets.Data.Enums;
public class MovieCategory
{
}
Error:
PM> add-migration initial
Build started...
Build succeeded.
System.InvalidOperationException: The entity type 'MovieCategory' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.
at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateNonNullPrimaryKeys(IModel model, IDiagnosticsLogger`1 logger)
at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model, IDiagnosticsLogger`1 logger)
Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
The entity type 'MovieCategory' requires a primary key to be defined. If you intended to use a keyless entity type, call 'HasNoKey' in 'OnModelCreating'. For more information on keyless entity types, see https://go.microsoft.com/fwlink/?linkid=2141943.
let me know what i am doing wrong.
CodePudding user response:
In Entity Framework, most entities have a unique identifier to reference them. The error messages Staates that your MovieCategory
class lacks such an identifier. Either add an Id
property to MovieCategory
:
public class MovieCategory
{
public int Id { get; set; }
}
If you intend to create a keyless entity, use the method described in the error message or mark the class with the Keyless
attribute (from EF Core 5):
[Keyless]
public class MovieCategory
{
}
More information on keyless entities can be found here.