实体框架核心:没有为此 dbcontext 定义无参数构造函数

时间:2021-02-26 16:14:28

标签: c# entity-framework-core

当我尝试使用 Entity Framework Core 生成新的脚手架时遇到问题。我收到一个错误

<块引用>

没有为此 dbcontext 定义无参数构造函数。

我尝试过任何解决方案,但没有任何效果。

这是我的 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);
        }
    }

我已将其添加到 Startup 方法内的 ConfigureService 文件中:

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

2 个答案:

答案 0 :(得分:1)

根据文档 https://docs.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli

如果 CLI 无法从依赖项容器获取上下文,它将尝试查找默认构造函数或设计时工厂。在您执行其中任何一项之前,您需要问自己为什么它无法在您的容器中找到上下文。

上下文是否在不同的项目中,然后是带有宿主构建器的项目,那么您需要使用 -s 标志来指定启动项目。

答案 1 :(得分:0)

尝试将以下内容添加到您的 DbContext 类中:

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