[英]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.当我尝试使用 Entity Framework Core 生成新的脚手架时遇到问题。 I get an error
我收到一个错误
No parameterless constructor defined for this dbcontext.
没有为此 dbcontext 定义无参数构造函数。
I've tried any solution but nothing works.我尝试了任何解决方案,但没有任何效果。
This is the my 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);
}
}
I've added this in my Startup
file inside the ConfigureService
method:我在
ConfigureService
方法内的Startup
文件中添加了这个:
services.AddDbContext<MyDbContext>
(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
As per documentation https://docs.microsoft.com/en-us/ef/core/cli/dbcontext-creation?tabs=dotnet-core-cli根据文档https://docs.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.如果 CLI 无法从依赖容器中获取上下文,它将尝试查找默认构造函数或设计时工厂。 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.是在不同项目中的上下文,然后是具有主机生成器的项目,那么您需要使用 -s 标志来指定启动项目。
Try adding the following to your DbContext
class:尝试将以下内容添加到您的
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.