I am writing a program that uses SQLite, and it seemed strange to me to open and close the connection every time I use the database, so I decided to use this in the context class. Is this a normal practice, or can it cause problems?
For example:
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace LUC.SqlFileTree
{
public class SqlContext : DbContext
{
public DbSet<Item> items { get; set; }
public string ConnectionString { get; set; }
private SqliteConnection connection;
public SqlContext (string connectionString)
{
ConnectionString = connectionString;
_ = Database.EnsureCreated();
}
protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder)
{
...
connection = new SqliteConnection(connectionStringBuilder.ToString());
connection.Open();
...
}
protected override void OnModelCreating (ModelBuilder modelBuilder)
{
...
}
public override void Dispose ()
{
connection.Close();
SqliteConnection.ClearAllPools();
GC.SuppressFinalize(this);
base.Dispose();
}
}
}
After that I work with the database like this:
using var context = new SqlContext(connectionString);
...
So far there have been no problems with this implementation, but I am afraid that in the future this approach will cause some bugs that will be difficult to find.
New contributor
TrickyShot is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.