我是新的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");
        }

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


当前回答

解决这个问题的简单方法

错误信息:

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

修复:

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

其他回答

正如Win的高分答案所提到的,你可能需要安装Microsoft.EntityFrameworkCore.SqlServer NuGet包,但请注意,这个问题使用的是asp.net core mvc。在最新的ASP。在NET Core 2.1中,微软包含了一个叫做微软. aspnetcore . app的元包

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/metapackage-app?view=aspnetcore-2.2

如果右键单击ASP. xml,就可以看到对它的引用。在解决方案资源管理器中选择“编辑项目文件”

如果ASP。NET core webapps using语句

<包引用包括=“Microsoft.AspNetCore.App” />

Microsoft.EntityFrameworkCore.SqlServer包含在这个元包中。所以在你的Startup.cs中,你只需要添加:

使用Microsoft.EntityFrameworkCore;

哇,这么多答案都没有提到这个Microsoft.EntityFrameworkCore.InMemory包!

将引用添加到这个包中: < PackageReference包括= " Microsoft.EntityFrameworkCore。InMemory" Version="2.2.2" />,你应该很好。

如果你在Sqlite的情况下面临这个问题,那么

. 我认为这是Sqlite版本的问题,当我使用这个版本的Sqlite时,我有同样的问题

2.2.4版:

在这里检查版本后,我改变了版本,然后它工作了。

使用后没有错误

2.1.2版:

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

PM > Install-Package Microsoft.EntityFrameworkCore.SqlServer

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

using Microsoft.EntityFrameworkCore;

我们添加数据库上下文:

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

从Nuget安装以下包

微软。EntityFrameworkCore Microsoft.EntityFrameworkCore.Sqlite.Core