7

I put my models in a class library with Core. I already did the first migration to test a part of my model, but after a big enhancement, I deleted my database and migration to have only one V1 migration.

The thing is, after this deletion, when I try to add-migration I get this error:

System.InvalidOperationException: The entity type 'CustomAttributeData' requires a primary key to be defined. at Microsoft.EntityFrameworkCore.Internal.ModelValidator.ShowError(String message) at Microsoft.EntityFrameworkCore.Internal.ModelValidator.Validate(IModel model) at Microsoft.EntityFrameworkCore.Internal.RelationalModelValidator.Validate(IModel model) at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator) at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel() at Microsoft.EntityFrameworkCore.Internal.LazyRef`1.get_Value() at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitTransient(TransientCallSite transientCallSite, ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass16_0.<RealizeService>b__0(ServiceProvider provider) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType) at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass3_0`1.<Execute>b__0() at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) The entity type 'CustomAttributeData' requires a primary key to be defined. 

I don't know why I am getting this error. All my models have a primary key defined with DataAnnotation.

If needed, I can provide the new models.

Here's the context if is related/helpful:

public class AmcContext : DbContext { public DbSet<User> Users { get; set; } public DbSet<Location> Location { get; set; } public DbSet<Rating> Rating { get; set; } public DbSet<RatingType> RatingType { get; set; } public DbSet<Subscription> Subscription { get; set; } public DbSet<Module> Module { get; set; } public AmcContext(): base() { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Ignore<User>(); modelBuilder.Entity<Client>().ToTable("Client"); modelBuilder.Entity<Professionnal>().ToTable("Professional"); base.OnModelCreating(modelBuilder); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(@"Server=localhost\SQLEXPRESS;Database=Askmycar;Trusted_Connection=True;"); base.OnConfiguring(optionsBuilder); } } 

Thanks.

3
  • 2
    It's seems like you have no defined a key for all your entities, you need to set key for each entity in your db context Commented Dec 25, 2016 at 5:48
  • I will recheck, but I think I didn't forget any primary or foreign key Commented Dec 25, 2016 at 10:11
  • 3
    I understand my errors, i tried to use Type for one one my properties and it ask for a primary key... Commented Dec 25, 2016 at 10:46

3 Answers 3

12

I actually wanted to use Type in my model, and I had already initialized the properties with a converter:

modelBuilder.Entity<...>() .Property(x => x.Type) .IsRequired() .HasConversion( convertToProviderExpression: x => x.AssemblyQualifiedName, convertFromProviderExpression: x => Type.GetType(x)); 

I assumed this would've been enough for Entity Framework Core to realize that Type is not an entity, but I ended up having to explicitly ignore it for this to work:

modelBuilder.Ignore<Type>(); 
Sign up to request clarification or add additional context in comments.

3 Comments

Same issue here. The error ist correct but could there be a hint about which entity is affected please...
This works for me without the Ignore<Type> statement (.NET Core 2.2)
Not working for me in .NET 6 :/
9

On one of my model I have a property like that :

public Type AvailableFor { get; set; } 

Type is an object so it was waiting for a primary key I change it to :

public string AvailableFor { get; set; } 

and its works.

Thanks to @H.Herzi :)

Comments

1

To reduce a misspelled error on your EF Core code, you can use a code generator tool, EF Core has a command line tool for code generation, in my case I use CatFactory and with code like this we can generate code from existing database:

var connectionString = "server=(local);database=Store;integrated security=yes;"; var dbFactory = new SqlServerDatabaseFactory() { ConnectionString = connectionString }; var db = dbFactory.Import(); var project = new EfCoreProject() { Name = "Store", Database = db, OutputDirectory = "C:\\Temp\\Store" }; project.BuildFeatures(); project .GenerateEntities() .GenerateAppSettings() .GenerateMappingDependences() .GenerateMappings() .GenerateDbContext() .GenerateContracts() .GenerateRepositories(); 

You can get more information on this link: Generating Code for EF Core with CatFactory

In that way we avoid to make a mistake on writing EF Core code

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.