本文介绍了如何使用petapoco创建DAL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用petapoco创建一个DAL和存储库。困难在于,我不知道它如何管理其连接。

I need to create a DAL and repositories using petapoco. The difficulty that comes in, is that I dont know how it manages its connections.

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

If I was using dapper I know how the connection process flows because I control it. I don't know what are the best practices in creating a DAL with petapoco.

 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); //我的DALHelper类中的这行
作为一个静态属性,但我担心可扩展性

I would like to place var db = new PetaPoco.Database("Sqlite_Connection");//this linein my DALHelper class as a static property but I'm worried about scalability

推荐答案

我不建议使用静态,因为您可能会收到错误,如,因为不同的请求使用相同的连接相同的资源。

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.

两个选项:

public class BaseController : Controller 
{
  protected DatabaseWithMVCMiniProfiler _database;

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

    _database = new DatabaseWithMVCMiniProfiler( "MainConnectionString");

  }
}



2。静态方法每个请求创建一个连接



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

这篇关于如何使用petapoco创建DAL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 21:45