“DbContextOptionsBuilder”未包含“UseSqlServer”的定义,并且找不到可接受第一个“DbContextOptionsBuilder”类型参数的可访问扩展方法“UseSqlServer”(是否缺少 using 指令或程序集引用?)

使用entity framework core时报如标题错误。

在startup.cs文件中配置服务

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
 
            //注册数据库上下文
            services.AddEntityFrameworkSqlServer().AddDbContext<SQLDbRWContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("Main_ReadAndWrite"));
            });
        }

解决方案

1、首先检查项目添加了Microsoft.EntityFrameworkCore和Microsoft.EntityFrameworkCore.SqlServer引用

2、需要手动在startup.cs中添加引用,不然无法识别扩展方法。

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.SqlServer;

唉,有点坑。

原文地址:https://www.cnblogs.com/chenxizhaolu/p/15156460.html