petapoco - 如何使用 petapoco 创建 DAL

标签 petapoco

关闭。这个问题是opinion-based .它目前不接受答案。












想改善这个问题吗?更新问题,以便可以通过 editing this post 用事实和引文回答问题.

2年前关闭。




Improve this question




我需要使用 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 类中作为静态属性,但我担心可扩展性

最佳答案

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

两种选择:

1. 在 Controller 基类中创建连接

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"];
  }
}

关于petapoco - 如何使用 petapoco 创建 DAL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7052350/

相关文章:

sql - 使用 PetaPoco 执行参数化存储过程

orm - PetaPoco 是否处理枚举?

c# - PetaPoco,将列表传递给存储过程

c# - PetaPoco - 设置事务隔离级别

c# - 如何使用 Petapoco 将自动增量 ID 设置为另一列

repository-pattern - 这是使用 petapoco 的工作单元和存储库模式(带有事务)的糟糕或错误设计/实现吗

c# - 具有可为空 Guid 的 PetaPoco ExecuteScalar

create-table - 使用 PetaPoco(和 NPoco)创建表的推荐方法是什么?

petapoco - 指定了参数 '@home' 但没有传递参数...错误消息

c# - PetaPoco - 如何关闭自动增量?