我应该在这里使用 "using" 语句还是保持原样?

Should I be using the "using" statement here or leave it as is?

几年前我发现了这种创建 DbContext 实例的方法,只是稍微更新了一下。 我的代码有效,但我想知道它是否会在未来引起任何问题。 我的问题是,我应该为我的上下文调用使用 "using" 语句还是保持原样?

这是 RAGEMP 的 GTA 5 修改版。服务器同步播放器并在需要时调用 MySQL 数据库。

public class DefaultDbContext : DbContext
{
    public DefaultDbContext(DbContextOptions options) : base(options)
    {

    }

    // Accounts table
    public DbSet<Account> Accounts { get; set; }

}

public class ContextFactory : IDesignTimeDbContextFactory<DefaultDbContext>
{
    private static DefaultDbContext _instance;

    public DefaultDbContext CreateDbContext(string[] args)
    {
        var builder = new DbContextOptionsBuilder<DefaultDbContext>();

        builder.
            UseMySql(@"Server=localhost;
                    database=efcore;
                    uid=root;
                    pwd=;",
                optionsBuilder => optionsBuilder.MigrationsAssembly(typeof(DefaultDbContext).GetTypeInfo().Assembly.GetName().Name));

        return new DefaultDbContext(builder.Options);
    }

    public static DefaultDbContext Instance
    {
        get
        {
            if (_instance != null) return _instance;

            return _instance = new ContextFactory().CreateDbContext(new string[] { });
        }
        private set { }
    }

// 其他地方

        // create a new Account object
        var account = new Account
        {
            Username = "test",
            Password = "test"
        };

        // Add this account data to the current context
        ContextFactory.Instance.Accounts.Add(account);

        // And finally insert the data into the database
        ContextFactory.Instance.SaveChanges();

如果您 DbContext 的生命周期很短,并且不尝试缓存它们或过度重用实例,则此方法没有任何问题。

但是,我个人觉得这有点冗长。对于内部应用程序,我倾向于将设置和连接字符串保留在 app.config 中,只使用 using 语句。

using(var db = new MyContext())
{
    var lotsOfStuff = db.SomeTable.Where(x => x.IsAwesome);
    //
}

话虽如此,您实际上只需要遵守几条规则(这不是一个自以为是的答案)

  1. 不要过度使用 DbContext。它们在内部缓存,创建和关闭它们的开销很小。
  2. 不要试图将一切都隐藏在不必要的抽象层之后。
  3. 始终首先为可读性和可维护性编写代码,除非您需要为性能编写代码。

更新

Maybe I am misunderstanding something but if I am saving changes to the database more often than not, is my approach then bad? Little things get updated when something is changed, not big chunk of data here and there

这取决于您打开 DefaultDbContext 的时间长短,我的意思是如果它仅用于一年中的几次查询就可以了。

上下文旨在相当快地打开和关闭,它们并不是为了长时间保持打开和活动而设计的。这样做有时会给您带来更多问题。

经常保存到数据库,虽然很有道理,但这并不是真正的问题。