如何使用petapoco创建DAL

Dav*_*vid 14 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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

Edu*_*eni 12

我不建议使用静态,因为您可能会收到"已存在与此命令关联的打开DataReader"之类的错误,因为访问相同资源的不同请求使用相同的连接.

两种选择:

1.在控制器基类中创建连接

public class BaseController : Controller 
{
  protected DatabaseWithMVCMiniProfiler _database;

  protected override void OnActionExecuting(ActionExecutingContext filterCon ) 
  {
    base.OnActionExecuting( filterCon );

    _database = new DatabaseWithMVCMiniProfiler( "MainConnectionString");

  }
}
Run Code Online (Sandbox Code Playgroud)

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"];
  }
}
Run Code Online (Sandbox Code Playgroud)