【问题标题】:How to unlock the Sqlite database file in EntityFramework.Core如何在 EntityFramework.Core 中解锁 Sqlite 数据库文件
【发布时间】:2022-06-10 22:16:22
【问题描述】:

我有一个在net6.0 上使用Microsoft.EntityFrameworkCore.Sqlite 6.0.5 的项目。我希望 Sqlite 数据库文件在 DbContext 被释放后解锁。

但是,我观察到的行为是 Sqlite 数据库在 DbContext 被处置和完成后仍处于锁定状态。有一个项目可以重现here的行为。

如何解锁数据库文件?

我的DbContext 看起来像这样:

public class MyContext : DbContext
{
    ~MyContext()
    {
        Console.WriteLine("Finaliser was called.");
    }

    public override void Dispose()
    {
        base.Dispose();
        Console.WriteLine("Dispose was called.");
    }

    public static readonly string DbFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "_temp.db");

    public DbSet<Foo> Summaries { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Foo>().HasKey(nameof(Foo.Id));
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlite($"Data Source={DbFile}");
    }
}

我是这样使用的:

public static void AddItem()
{
    using var ctx = new MyContext();
    ctx.Database.EnsureCreated();
    ctx.Summaries.Add(new Foo {Bar = "Foo"});
    ctx.SaveChanges();        
}

【问题讨论】:

    标签: c# sqlite entity-framework-core


    【解决方案1】:

    ClearAllPools() 或在连接字符串中不指定池 (Pooling=false)

    https://docs.microsoft.com/en-us/dotnet/standard/data/sqlite/connection-strings#pooling

    【讨论】:

      猜你喜欢
      • 2022-10-09
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 2013-05-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      相关资源
      最近更新 更多