简体   繁体   中英

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

I found out this way of creating DbContext instances a few years ago and only updated it slightly. My code works, but I am wondering if it will cause any problems in the future. My question is, should I use the "using" statement for my context calls or leave it as is?

This is for RAGEMP, a GTAV modification. Server syncs players and makes calls to the MySQL database when needed.

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 { }
    }

// somewhere else

        // 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();

There is nothing wrong with this approach if you are keeping your DbContext short lived and not trying to cache them or overly reuse an instance.

However, personally i find this a little verbose. For inhouse-applications, i tend to keep setup and connection strings in app.config and just use the using statement .

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

On saying that, there is really only a few rules you need to abide by (without this being an opinionated answer)

  1. Don't try to overly use a DbContext . They are internally cached, and there is little overhead in creating them and closing them.
  2. Don't try to hide everything behind layers of abstractions unnecessarily.
  3. Always code for readability and maintainability first, unless you have a need to code for performance.

Update

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

It depends how long you are keeping open your DefaultDbContext , I mean if its only for a couple of queries year thats fine.

Context are designed to be opened and closed fairly quickly, they are not designed to stay open and alive for long periods of time. Doing so will sometimes cause you more issues than not.

Saving to the database often, while making perfect sense, its not really the issue here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM