本文介绍了实体框架核心:DbContextOptionsBuilder 不包含“usesqlserver"的定义并且没有扩展方法“usesqlserver"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 EF Core 的新手,我正在尝试让它与我的 ASP.NET Core 项目一起工作.

I am new to EF core and I'm trying to get it to work with my ASP.NET Core project.

尝试将 DbContext 配置为使用来自配置的连接字符串时,我在 startup.cs 中收到上述错误.我正在关注本教程.

I get the above error in my startup.cs when trying configure the DbContext to use a connection string from config. I am following this tutorial.

有问题的代码在startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using tracV2.models;
using tracV2.data;

namespace tracV2
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();

            services.AddSingleton<IConfiguration>(Configuration);

            string conn = Configuration.GetConnectionString("optimumDB");

            services.AddDbContext<tracContext>(options => options.usesqlserver(conn));
        }

UseSqlServer 方法如果我直接放到上下文中就可以识别:

The UseSqlServer method is recognized if I put it directly into the context:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace tracV2.data
{
    public class tracContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("myrealconnectionstring");
        }

我所有的在线研究都指向缺失的参考文献,但我似乎无法找出我遗漏了哪一个 (见图片).

All my research online points to missing references, but I can't seem to find out which one I am missing (see image).

推荐答案

首先我们安装 Microsoft.EntityFrameworkCore.SqlServer NuGet 包:

First we install the Microsoft.EntityFrameworkCore.SqlServer NuGet Package:

PM > Install-Package Microsoft.EntityFrameworkCore.SqlServer

然后,导入命名空间后

using Microsoft.EntityFrameworkCore;

我们添加数据库上下文:

we add the database context:

services.AddDbContext<AspDbContext>(options =>
    options.UseSqlServer(config.GetConnectionString("optimumDB")));

这篇关于实体框架核心:DbContextOptionsBuilder 不包含“usesqlserver"的定义并且没有扩展方法“usesqlserver"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 21:34