stefano toppi
stefano toppi

Reputation: 11

Entity Framework Core: No parameterless constructor defined for this dbcontext

I have a problem when I try to generate a new scaffold with Entity Framework Core. I get an error

No parameterless constructor defined for this dbcontext.

I've tried any solution but nothing works.

This is the my dbContext:

public class MyDbContext: DbContext
{
        public MyDbContext(DbContextOptions<MyDbContext> options)
        : base(options)
        {
        }

        public DbSet<Player> Players { get; set; }
        public DbSet<PlayerAdvanceStats> PlayerAdvanceStats { get; set; }
        public DbSet<Account> Accounts { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Player>()
            .HasOne(a => a.PlayerAdvanceStats)
            .WithOne(a => a.player)
            .HasForeignKey<PlayerAdvanceStats>(c => c.PlayerId);
        }
    }

I've added this in my Startup file inside the ConfigureService method:

services.AddDbContext<MyDbContext>
                (options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

Upvotes: 0

Views: 2050

Answers (2)

verbedr
verbedr

Reputation: 2270

As per documentation https://learn.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli

If the CLI can't get the context from the dependency container it will either try to find a default constructor or a design time factory. Before you do either of those you need to ask yourself why it can't find the context in your container.

Is the context in a different project then the project with the host builder then you need to use the -s flag to specify the startup project.

Upvotes: 1

WaitingForGuacamole
WaitingForGuacamole

Reputation: 4301

Try adding the following to your DbContext class:

public class MyDbContext: DbContext
{
        // try adding the parameterless constructor indicated by the error
        public MyDbContext() : base() { }

        public MyDbContext(DbContextOptions<MyDbContext> options)
        : base(options)
        {
        }

        public DbSet<Player> Players { get; set; }
        public DbSet<PlayerAdvanceStats> PlayerAdvanceStats { get; set; }
        public DbSet<Account> Accounts { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Player>()
            .HasOne(a => a.PlayerAdvanceStats)
            .WithOne(a => a.player)
            .HasForeignKey<PlayerAdvanceStats>(c => c.PlayerId);
        }
    }
}

Upvotes: 0

Related Questions