gpt4 book ai didi

petapoco - 如何使用 petapoco 创建 DAL

转载 作者:行者123 更新时间:2023-12-03 22:24:13 24 4
gpt4 key购买 nike

关闭。这个问题是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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com