【问题标题】:Having trouble with UseInMemoryDatabase ASP.NET Core 3.1UseInMemoryDatabase ASP.NET Core 3.1 遇到问题
【发布时间】:2020-12-01 03:36:23
【问题描述】:

我正在使用本教程:Create a web API with ASP.NET Core,但在从 Nuget 安装 Microsoft.EntityFrameworkCore.SqlServer 后,Startup.cs 出现错误。

错误信息是:

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

该指令指的是项目“注册数据库上下文”中的这一点。

这里是startup.cs的代码:

using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using TodoApi.Models;

namespace TodoApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<TodoContext>(opt =>
               opt.UseInMemoryDatabase("TodoList"));
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

我上网查了一下,没找到解决这个问题的办法,只能说我安装了Microsoft.EntityFrameworkCore.SqlServer 5.0版,教程里是3.0版,不过我觉得不是这个问题。

我得到的错误发生在这里:

services.AddDbContext<TodoContext>(opt =>
               opt.UseInMemoryDatabase("TodoList"));

【问题讨论】:

  • 您必须安装 InMemory 软件包 - 注明 here。您还应该注意 The in-memory database is designed for testing only 根据文档。
  • 安装Microsoft.EntityFrameworkCore.InMemory
  • @Jonesopolis 那么我应该使用什么?还是用这个没问题,按照教程做?
  • @MateiAnghel 肯定会坚持本教程中的内容。我只是想让你知道这个包不应该在任何“真实”代码中使用
  • @Jonesopolis 非常感谢,这解决了我的问题

标签: c# asp.net asp.net-core


【解决方案1】:

您使用的文章说明您需要在Add a Database Context 部分中添加Microsoft.EntityFrameworkCore.InMemory 包,在Add NuGet packages 框中:

使用上述说明添加 Microsoft.EntityFrameworkCore.InMemory NuGet 包

这个包添加了提供者UseInMemoryDatabase扩展方法

【讨论】:

    【解决方案2】:

    尝试添加包:Microsoft.EntityFrameworkCore.InMemory

    【讨论】:

      猜你喜欢
      • 2020-11-15
      • 2021-02-11
      • 2020-11-28
      • 1970-01-01
      • 2021-05-25
      • 2020-07-30
      • 1970-01-01
      • 2021-01-30
      • 2020-08-09
      相关资源
      最近更新 更多