是否有使用数据库不可知的方法来执行带参数的存储过程

时间:2018-08-28 15:02:25

标签: entity-framework-core

使用Entity Framework Core 2.1,我有一些调用存储过程的代码,并传入一些参数。在执行过程中,我们使用的是Sql Server,一切正常。但是,我们的测试用例使用Sqlite运行。是否有一种体面的方法(不会过度污染代码,而只是为了支持测试而添加了不需要的代码),无论实际使用哪个数据库,该代码都能运行?

当前有问题的代码如下:

await MyContext.Database.ExecuteSqlCommandAsync("UpdateEndDate @p0, @p1, @p2", id, from, thru);

并导致SqliteException:

Microsoft.Data.Sqlite.SqliteException
  HResult=0x80004005
  Message=SQLite Error 1: 'near "UpdateEndDate": syntax error'.
  Source=Microsoft.Data.Sqlite
  ...

(还想知道为什么会有SqlParameter和SQLiteParameter?为什么不能有数据库不可知参数类?)

测试工具中的DBContext配置如下:

public static SqliteConnection GetConnection()
{
    SqliteConnection connection = new SqliteConnection("DataSource=:memory:");
    connection.Open();

    connection.CreateFunction(
    "NEWID",
    Guid.NewGuid(),
    g => g);

    return connection;
}

serviceProvider = new ServiceCollection()
    .<snipped>
    .AddEntityFrameworkSqlite()
    .AddDbContext<MyContext>(
    (theServiceProvider, opt) => opt
    .UseInternalServiceProvider(theServiceProvider)
    .UseSqlite(GetConnection()))
    .BuildServiceProvider();

MyContext cc = serviceProvider.GetService(typeof(MyContext)) as MyContext;
cc.Database.EnsureCreated();

1 个答案:

答案 0 :(得分:0)

您是否考虑过使用DbProviderFactory类?它在Core 2.1中可用。将两个连接字符串都放在appSettings.json中,并在启动时根据运行时所在的环境设置适当的DbContext。

https://docs.microsoft.com/en-us/dotnet/api/system.data.common.dbproviderfactory?view=netcore-2.1