public class BaseController : Controller
{
protected DatabaseWithMVCMiniProfiler _database;
protected override void OnActionExecuting(ActionExecutingContext filterCon )
{
base.OnActionExecuting( filterCon );
_database = new DatabaseWithMVCMiniProfiler( "MainConnectionString");
}
}
2. 静态方法为每个请求创建一个连接
public static class DbHelper {
public static Database CurrentDb() {
if (HttpContext.Current.Items["CurrentDb"] == null) {
var retval = new DatabaseWithMVCMiniProfiler("MainConnectionString");
HttpContext.Current.Items["CurrentDb"] = retval;
return retval;
}
return (Database)HttpContext.Current.Items["CurrentDb"];
}
}
1. Create the connection in a controller base class
public class BaseController : Controller
{
protected DatabaseWithMVCMiniProfiler _database;
protected override void OnActionExecuting(ActionExecutingContext filterCon )
{
base.OnActionExecuting( filterCon );
_database = new DatabaseWithMVCMiniProfiler( "MainConnectionString");
}
}
2. Static method creating one connection per request
public static class DbHelper {
public static Database CurrentDb() {
if (HttpContext.Current.Items["CurrentDb"] == null) {
var retval = new DatabaseWithMVCMiniProfiler("MainConnectionString");
HttpContext.Current.Items["CurrentDb"] = retval;
return retval;
}
return (Database)HttpContext.Current.Items["CurrentDb"];
}
}
A static property will be fine for the Initialization. PetaPoco will open and close the connection each time, unless you are using a transaction. This isn't usually an issue due to connection pooling.
If you are using this in a web application then you should instantiate one PetaPoco database per request.
发布评论
评论(2)
我不建议使用静态,因为您可能会收到类似 "There is already an open DataReader关联的错误此命令”,因为访问同一资源的不同请求使用同一连接。
两种选项:
1. 在控制器基类中创建连接
2. 静态方法为每个请求创建一个连接
I don't recommend using a static since you can get errors like "There is already an open DataReader associated with this Command" because the same connection is used by different request accesing the same resource.
Two options:
1. Create the connection in a controller base class
2. Static method creating one connection per request
静态属性适合初始化。
PetaPoco 每次都会打开和关闭连接,除非您正在使用事务。由于连接池,这通常不是问题。
如果您在 Web 应用程序中使用它,那么您应该为每个请求实例化一个 PetaPoco 数据库。
A static property will be fine for the Initialization.
PetaPoco will open and close the connection each time, unless you are using a transaction. This isn't usually an issue due to connection pooling.
If you are using this in a web application then you should instantiate one PetaPoco database per request.