有没有办法直接查询Entity Framework Core使用的内存数据库?

SBF*_*ies 5 .net c# database entity-framework-core

我正在使用内存数据库提供程序对 .Net Core 2.2 应用程序进行一些测试。我需要使应用程序中的一个表无法访问 - 通过重命名或删除它。有没有办法直接对内存数据库运行这种查询?我尝试使用以下方式建立连接:

context.Database.GetDbConnection();
Run Code Online (Sandbox Code Playgroud)

但这会引发错误

仅当上下文使用关系数据库提供程序时,才能使用特定于关系的方法。

我知道我可以通过以下方式销毁整个数据库:

context.Database.EnsureDeleted();
Run Code Online (Sandbox Code Playgroud)

但我需要保留它并且只销毁或重命名一张表。

rhy*_*nix 4

InMemory提供程序不受关系数据库支持,并且具有一组不支持您的情况的不同操作。

您可以改为使用 SQLite 内存模式 ( doc ),然后创建一个拦截器来拦截发出的 EF 命令,并抑制表的创建,或抑制针对该表的其他查询。

public class MyInterceptor : DbCommandInterceptor {
    public override InterceptionResult<int> NonQueryExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<int> result) {
        if (ContainsBannedTable(command)) {
            //suppress the operation
            result = InterceptionResult<int>.SuppressWithResult(0);
        }
        return base.NonQueryExecuting(command, eventData, result);
    }

    private bool ContainsBannedTable(DbCommand command) {
        //or custom logic
        return command.CommandText.Contains("ToDeleteEntity");
    }
}
Run Code Online (Sandbox Code Playgroud)

Microsoft.EntityFrameworkCore.DbUpdateException... SqliteException: SQLite Error 1: 'no such table: ToDeleteEntity'当尝试访问不需要的表时,以下将抛出异常( )。

var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<MyContext>()
                  .UseSqlite(connection)
                  .AddInterceptors(new MyInterceptor())
                  .Options
                  ;

var context = new MyContext(options);
context.Database.EnsureCreated();

context.AllowedEntity.Add(new AllowedEntity { Id = 1 });
context.SaveChanges();
Console.WriteLine(context.AllowedEntity.FirstOrDefault()?.Id); //1 - ok

context.ToDeleteEntity.Add(new ToDeleteEntity { Id = 1 });
//will throw an exception
context.SaveChanges();
Console.WriteLine(context.ToDeleteEntity.FirstOrDefault()?.Id);

//close the connection and clean up
//...
Run Code Online (Sandbox Code Playgroud)
public class MyContext : DbContext {
    public MyContext(DbContextOptions options) : base(options) {
    }

    public DbSet<AllowedEntity> AllowedEntity { get; set; }
    public DbSet<ToDeleteEntity> ToDeleteEntity { get; set; }
}

public class ToDeleteEntity {
    public int Id { get; set; }
}

public class AllowedEntity {
    public int Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)