nik*_*ita 7 c# linq lambda linq2db
假设我有一些使用伪ORM的伪代码(在我的情况下,它是Linq2Db).
static IEnumerable<A> GetA()
{
using (var db = ConnectionFactory.Current.GetDBConnection())
{
return from a in db.A
select a;
}
}
static B[] DoSmth()
{
var aItems = GetA();
if (!aItems.Any())
return null;
return aItems.Select(a => new B(a.prop1)).ToArray();
}
Run Code Online (Sandbox Code Playgroud)
Connection什么时候关闭db
?在那种情况下它会被关闭吗?将关闭什么连接 - 使用语句或lambda表达式中的连接?.NET编译器正在为lambdas创建匿名类,因此它将复制到该类的连接.什么时候关闭?
不知怎的,我设法得到了Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
物化查询,异常消失了.但我想知道这件事是如何运作的.
这完全取决于您的 ORM。如果处理ConnectionFactory.Current.GetDBConnection()
关闭连接,那么您将永远无法枚举结果。如果它没有关闭连接(和其他东西关闭),它可能会工作,具体取决于其他人是否关闭了连接。
在任何情况下,您可能都不想从创建和处理连接的事物中返回未枚举的可枚举。
要么在关闭集合之前枚举它,例如:
static IEnumerable<A> GetA()
{
using (var db = ConnectionFactory.Current.GetDBConnection())
{
return (from a in db.A
select a).ToArray();
}
}
Run Code Online (Sandbox Code Playgroud)
或在枚举结果的级别控制连接,例如:
static IEnumerable<A> GetA(whatevertype db)
{
return from a in db.A
select a;
}
static B[] DoSmth()
{
using (var db = ConnectionFactory.Current.GetDBConnection())
{
var aItems = GetA(db);
if (!aItems.Any())
return null;
return aItems.Select(a => new B(a.prop1)).ToArray();
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
538 次 |
最近记录: |