gpt4 book ai didi

c# - 如何在 EF Core 中实例化 DbContext

转载 作者:可可西里 更新时间:2023-11-01 03:11:49 25 4
gpt4 key购买 nike

我还设置了 .net 核心项目和数据库上下文。但是由于这个错误,我还不能开始使用 dbContext-

"there is no argument given that corresponds to the required formalparameter 'options'"

Controller :

public IActionResult Index()
{
using (var db = new BlexzWebDb())
{

}
return View();
}

数据库上下文代码:

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

public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<AssignedRole> AssignedRoles { get; set; }

}

附上错误图片。如何解决此问题?

pic

最佳答案

从ConnectionString实例化新的DbContext对象

var connectionstring = "Connection string";

var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer(connectionstring);


ApplicationDbContext dbContext = new ApplicationDbContext(optionsBuilder.Options);

// Or you can also instantiate inside using

using(ApplicationDbContext dbContext = new ApplicationDbContext(optionsBuilder.Options))
{
//...do stuff
}

关于c# - 如何在 EF Core 中实例化 DbContext,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50788272/

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