最近我在浏览微型ORM,我喜欢Massive的SQLite版本(链接),因为它很简单。但是现在我遇到了一个问题。
我只是运行一些select语句,然后执行一个update语句,但是我遇到了一个异常。以下是我的代码:
var tbl = new Cust();
var customers = tbl.All(where: "CustomerID > @0", orderBy: "FirstName", columns: "CustomerID,FirstName", args: 4);
var firstCustomerName= customers.First().FirstName;
var c = tbl.Update(new { FirstName = "Updated2" }, 4); //Exception is here!
//Same happens even when using another object
//var tbl2 = new Cust();
//tbl2.Update(new { FirstName = "UpdatedName" }, 4);//Exception is here!
异常消息是:"Database is locked",出现在 Massive.SQLite 源代码中以下方法中。
public virtual int Execute(IEnumerable<DbCommand> commands)
{
var result = 0;
using (var conn = OpenConnection())
{
using (var tx = conn.BeginTransaction())
{
foreach (var cmd in commands)
{
cmd.Connection = conn;
cmd.Transaction = tx;
result += cmd.ExecuteNonQuery();
}
tx.Commit();//Here is the Exception!
}
}
return result;
}
当我查看 Massive.SQLite 源代码时,我发现 massive 从不关闭连接,而是依赖 using 语句来释放连接对象,就像上面的代码所示。
上面代码中的 OpenConnection() 是一个方法,每次调用都会返回一个新的连接。
public virtual DbConnection OpenConnection()
{
var result = _factory.CreateConnection();
result.ConnectionString = ConnectionString;
result.Open();
return result;
}
如果问题在于Massive没有关闭连接,并且根据这个SO问题,Sqlite不擅长并发连接,我应该关闭它,但是我无法访问连接,那我该如何关闭它呢?
我想听听使用Massive和SQLite的开发人员的最佳实践。