我在 .NET Core 应用程序中设置集成测试,但在第 53 行(即
appContext.Database.EnsureCreated()
)中出现错误:
$exception {“SQLite 错误 1:'靠近“''”:语法错误'。”}
Microsoft.Data.Sqlite.SqliteException
谁能告诉我出了什么问题吗?
using Asp.Versioning;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System.Data.Common;
using System.Xml.Linq;
using World.Persistence.DBContext;
namespace World.Integration.Tests
{
public abstract class CustomWebApplicationFactory<TProgram>
: WebApplicationFactory<TProgram> where TProgram : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
var dbContextDescriptor = services.SingleOrDefault(
d => d.ServiceType ==
typeof(DbContextOptions<WorldDBContext>));
services.Remove(dbContextDescriptor!);
var dbConnectionDescriptor = services.SingleOrDefault(
d => d.ServiceType ==
typeof(DbConnection));
_ = services.Remove(dbConnectionDescriptor!);
// Create open SqliteConnection so EF won't automatically close it.
services.AddSingleton<DbConnection>(container =>
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
return connection;
});
services.AddDbContext<WorldDBContext>((container, options) =>
{
var connection = container.GetRequiredService<DbConnection>();
options.UseSqlite(connection);
});
var sp = services.BuildServiceProvider();
using var scope = sp.CreateScope();
using var appContext = scope.ServiceProvider.GetRequiredService<WorldDBContext>();
try
{
appContext.Database.EnsureCreated();
}
catch (Exception)
{
throw;
}
});
builder.UseEnvironment("Development");
}
}
}
我用您的代码重现了您的问题,这是由 DbContexnt 中的
.HasDefaultValueSql()
方法中的 Sql 无效引起的,将其删除,用有效的 Sql 重新替换它,或者仅调用 HasDefaultValue() 将有助于解决您的问题