Search code examples
ormdatabase-connectionpetapoco

How to identify PetaPoco connections same or different within a transaction?


var db=(PetaPoco.Database)HttpContext.Current.Items["application_db"];
using(var t=db.GetTransaction())
{
    // some code
    db.Save(obj1);
    OwnExecute();
    db.Save(obj3);
    t.Complete();
}
public void OwnExecute(obj2)
{
    // some code
    var Owndb=(PetaPoco.Database)HttpContext.Current.Items["appdb"];
    Owndb.Save(obj2);
}

In this case I have Two Database Object (db and Owndb).Sometimes Transaction work not properly because Two connections are different.So i need to identify each connect like by connect_id or Please Share your Opinion or Ideas.


Solution

  • Since is advisable to use the same connection through the request, I have this two static methods:

    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"];
        }
    
        public static Database NewDb() {
            return new DatabaseWithMVCMiniProfiler("MainConnectionString");
        }
    

    And then you are assured that you are using the same connection

    var db=dbHelper.CurrentDb();
    using(var t=db.GetTransaction())
    {
        // some code
        db.Save(obj1);
        OwnExecute();
        db.Save(obj3);
        t.Complete();
    }
    public void OwnExecute(obj2)
    {
        // some code
        var Owndb=dbHelper.CurrentDb();
        Owndb.Save(obj2);
    }