如何使用petapoco创建DAL

时间:2011-08-13 18:10:17

标签: petapoco

我需要使用petapoco创建DAL和存储库。我遇到的困难是,我不知道它如何管理它的联系。

如果我使用的是dapper,我知道连接过程是如何流动的,因为我控制它。我不知道用petapoco创建DAL的最佳做法是什么。

 public class UserRepository
    {
        public IEnumerable<User> All()
        {
            var db = new PetaPoco.Database("Sqlite_Connection");//this line
            var s = db.Query<User>("SELECT * FROM Users");
            return s.ToList();
        }
    }

我想放置var db = new PetaPoco.Database("Sqlite_Connection");//this line 在我的DALHelper类中作为静态属性,但我担心可伸缩性

2 个答案:

答案 0 :(得分:12)

我不建议使用静态,因为您可能会收到"There is already an open DataReader associated with this Command"之类的错误,因为访问相同资源的不同请求使用相同的连接。

两个选项:

1。在控制器基类

中创建连接
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 :(得分:3)

静态属性对初始化没有问题。 除非您使用交易,否则PetaPoco每次都会打开和关闭连接。由于连接池,这通常不是问题。

如果您在Web应用程序中使用它,那么您应该根据请求实例化一个PetaPoco数据库。

相关问题