【发布时间】: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