entity-framework - 调用新的 DbContext 时,DbContextOptions 中的内容是什么?

标签 entity-framework asp.net-core entity-framework-core

我没有使用 DI,只是想从我的 Controller 中调用 DbContext。我正在努力弄清楚“选项”应该是什么?

应用程序数据库上下文.cs

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{

    public DbSet<Gig> Gigs { get; set; }
    public DbSet<Genre> Genres { get; set; }


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

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
    }
}

演出 Controller .cs
    public class GigsController : Controller
{
    private ApplicationDbContext _context;

    public GigsController()
    {
        _context = new ApplicationDbContext();
    }


    public IActionResult Create()
    {
        var viewModel = new GigFormViewModel
        {
            Genres = _context.Genres.ToList()
        };


        return View(viewModel);
    }
}

问题出在我的 GigsController 构造函数中:
_context = new ApplicationDbContext();

我出错了,因为我需要向 ApplicationDbContext 传递一些东西。没有给出对应于 'ApplicationDbContext.ApplicationDbContext(DbContextOptions)' 的必需形式参数 'options' 的参数

我尝试在从 base() 派生的 ApplicationDbContext 中创建一个默认构造函数,但这也不起作用。

在我的 startup.cs 中,我已经配置了 ApplicationDbContext
        public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        services.AddMvc();

        // Add application services.
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
    }

最佳答案

如果您 真的想要手动创建上下文,那么你可以 configure它像这样:

var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer(Configuration.GetConnectionStringSecureValue("DefaultConnection"));
_context = new ApplicationDbContext(optionsBuilder.Options); 

( DbContextOptionsBuilder<ApplicationDbContext> 类是 optionsservices.AddDbContext<ApplicationDbContext>(options => 参数的类型)。
但是在 Controller 中,您无权访问 Configuration对象,因此您必须将其作为 Startup.cs 中的静态字段公开或者使用其他一些技巧,这都是不好的做法。

最佳获取方式ApplicationDbContext是通过 DI 获取它:
public GigsController(ApplicationDbContext context)
{
    _context = context;
}

DI 容器将负责实例化 和处置 ApplicationDbContext .请注意,您已在 Startup.cs 中正确配置了所有内容。 :
services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

那就是配置 DI,为什么不直接使用它呢?

关于 DbContext 的默认构造函数的更多说明:在 EF6 中是这样完成的:public ApplicationDbContext(): base("DefaultConnection") {} .然后基础对象将使用 System.Configuration.ConfigurationManager静态类获取名为DefaultConnection的连接字符串来自 web.config .新的 Asp.net Core 和 EF Core 旨在尽可能解耦,因此不应依赖于任何配置系统。相反,您只需传递一个 DbContextOptions对象 - 创建该对象并配置它是一个单独的问题。

关于entity-framework - 调用新的 DbContext 时,DbContextOptions 中的内容是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38417051/

相关文章:

entity-framework - 为什么是 Entity Framework Dll 中的 TableAttribute?

c# - ASP.NET MVC 下拉列表未选择值

c# - Entity Framework Core 2.1 中特定环境的播种数据

multithreading - 如何在 Linux (Kubernetes) 上解决 ASP.NET Core 中的线程不足问题?

linux - Linux 上不支持 EF Core 平台

c# - 如何根据不同对象类型的另一个列表从数据库中获取列表?

c# - 如何从代码应用部分迁移?

entity-framework - Entity Framework 、应用层和关注点分离

c# - 如何使用动态生成的 ADO.NET 实体数据模型代码进行单元测试

.net - HttpClient DelegatingHandler 意外的生命周期