gpt4 book ai didi

c# - 使用配置调用了 AddDbContext,但是上下文类型 'ContextClass' 只声明了一个无参数构造函数?

转载 作者:行者123 更新时间:2023-11-30 12:38:48 25 4
gpt4 key购买 nike

详情

我正在尝试创建 asp.net 核心应用程序并使用 scaffold-dbcontext 生成类。当我运行这个应用程序时,它向我显示错误。我已经按照相同问题在 stackoverflow 上找到了一些答案,但我的问题仍然存在。 Question

我的语境

public partial class MyContext: DbContext
{

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


public virtual DbSet<Answer> Answer { get; set; }
public virtual DbSet<Attachment> Attachment { get; set; }
public virtual DbSet<Category> Category { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{

if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(@"Server=.;Database=MyContext;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder modelBuilder) { .... }
}

启动.cs

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();

services.AddMvc()
.AddJsonOptions(options =>
options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All);

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

}

错误

AddDbContext was called with configuration, but the context type 'MyContext ' only declares a parameterless constructor. This means that the configuration passed to AddDbContext will never be used. If configuration is passed to AddDbContext, then 'MyContext ' should declare a constructor that accepts a DbContextOptions and must pass it to the base constructor for DbContext.

最佳答案

在 appsetting.json 文件中使用名称“DefaultConnection”声明您的连接字符串

"Data": {
"DefaultConnection": "Data Source=(local); Initial Catalog=DBname; Integrated Security=True"
}

关于c# - 使用配置调用了 AddDbContext,但是上下文类型 'ContextClass' 只声明了一个无参数构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49691617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com