首先,我无法使用 SQL Lite。其次,下面的代码给了我:
Error CS1061 'DbContextOptionsBuilder' does not contain a definition for 'UseInMemoryDatabase' and no extension method 'UseInMemoryDatabase' accepting a first argument of type 'DbContextOptionsBuilder' could be found (are you missing a using directive or an assembly reference?)
代码:
var options = new DbContextOptionsBuilder<ProductContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
var context = new ProductContext(options);
上下文
using Memory.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace Memory.Data
{
public class ProductContext : DbContext
{
public ProductContext(DbContextOptions<ProductContext> options) : base(options)
{
}
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
}
}
我的项目CSPROJ文件
<ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.5" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.6" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.2" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.3" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.3" />
</ItemGroup>
确切的问题是该方法不可用。我似乎不明白为什么。我需要关于这个问题的启发。
最佳答案
根据EF Core: Testing with InMemory引用,需要添加Microsoft.EntityFrameworkCore.InMemory包以将 UseInMemoryDatabase()
扩展方法与 DbContextOptionsBuilder
结合使用:
Install-Package Microsoft.EntityFrameworkCore.InMemory
之后,您可以按照“编写测试”部分中给出的示例进行操作,如下所示:
var options = new DbContextOptionsBuilder<ProductContext>().UseInMemoryDatabase(databaseName: "database_name").Options;
using (var context = new ProductContext(options))
{
// add service here
}
关于c# - 为什么我无法调用 DbContextOptionsBuilder 上的 UseInMemoryDatabase 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48061096/