You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core内存SQLite数据库集成测试报错求助

SQLite Error 1: 'near "''": syntax error' 排查方案(EF Core集成测试EnsureCreated场景)

在.NET Core集成测试中,使用内存SQLite数据库时,调用appContext.Database.EnsureCreated()触发以下错误:

SQLite Error 1: 'near "''": syntax error'.

测试工厂代码如下:

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");
        }
    }
}

排查与解决步骤

  1. 检查实体模型的注解配置
    这类单引号语法错误,几乎都是EF Core生成SQL时出现了多余单引号,优先检查实体类的注解:

    • 排查是否存在[Column("''SomeColumn''")]这类错误的列名注解,多写了重复单引号
    • 检查[Table]、[Index]等其他数据注解的字符串参数,是否有单引号使用错误
  2. 开启EF Core日志定位错误SQL
    在AddDbContext配置中添加日志输出,查看生成的SQL语句,直接定位出错的表或字段:

    services.AddDbContext<WorldDBContext>((container, options) =>
    {
        var connection = container.GetRequiredService<DbConnection>();
        options.UseSqlite(connection)
               .LogTo(Console.WriteLine, LogLevel.Information); // 添加日志
    });
    

    运行测试后,查看控制台输出的SQL语句,找到触发错误的那条,即可定位到对应的实体配置问题。

  3. 检查Fluent API配置
    如果使用Fluent API定义实体映射,排查是否有类似entity.Property(e => e.Name).HasColumnName("''Name''")的错误配置,导致生成的SQL包含多余单引号。

  4. 验证版本兼容性
    确保Microsoft.EntityFrameworkCore.Sqlite、Microsoft.Data.Sqlite的版本与项目使用的.NET Core版本完全匹配,版本不兼容可能导致SQL生成逻辑异常。

  5. 临时切换为文件数据库辅助排查
    把内存SQLite连接字符串改为文件模式(如DataSource=test_integration.db),运行测试后查看生成的数据库文件,直接检查表结构是否有异常字段名,快速定位问题点。

内容的提问来源于stack exchange,提问作者Akash Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 04:35:19