我是新的EF核心,我试图让它与我的ASP工作。NET Core项目。

当我尝试配置DbContext使用config中的连接字符串时,我在startup.cs中得到了上述错误。我正在遵循这个教程。

有问题的代码在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方法直接放到上下文中,它就会被识别出来:

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");
        }

我在网上的所有研究都指向了缺失的参考文献,但我似乎找不到我缺失的是哪一本(见图)。


当前回答

目前正在使用实体框架核心3.1.3。以上的解决方案都不能解决我的问题。

但是,在我的项目上安装包microsoft . entityframeworkcore .代理解决了这个问题。现在我可以访问uselazyloadingagents()方法调用时设置我的DBContext选项。

希望这能帮助到一些人。请看下面的文章:

EF核心的惰性加载

其他回答

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

PM > Install-Package Microsoft.EntityFrameworkCore.SqlServer

然后,在导入命名空间之后

using Microsoft.EntityFrameworkCore;

我们添加数据库上下文:

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

解决这个问题的简单方法

错误信息:

解决方案: 安装“microsoft.entityframeworkcore”。sqlserver"与NuGet

修复:

PS:确保你在“using Microsoft.EntityFrameworkCore;”内容上使用了EF。

对我来说,这个问题发生在Visual Studio Code中,我能够通过2个步骤来修复:

使用Microsoft.EntityFrameworkCore手动添加; 在终端中运行dotnet构建。

目前正在使用实体框架核心3.1.3。以上的解决方案都不能解决我的问题。

但是,在我的项目上安装包microsoft . entityframeworkcore .代理解决了这个问题。现在我可以访问uselazyloadingagents()方法调用时设置我的DBContext选项。

希望这能帮助到一些人。请看下面的文章:

EF核心的惰性加载

我添加SqlServer和Sqlite到我的项目,同样的问题出现了。

对我来说,我安装了微软。EntityFrameworkCore之前的版本是5.0.6。现在Microsoft.EntityFrameworkCore.SqlServer的版本是5.0.7。安装后没有UserSqlServer方法。

1. 请尝试升级工具版本以保持一致

尝试在csproj中修改版本:

<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.7">

或者打开NuGet来更新包。

2. 重新启动Visual Studio

如果它不能帮助你,最重要的是重新启动VS

然后,一切都好了。

参考 https://github.com/dotnet/efcore/issues/7891