Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Chris Randle 67 posts 181 karma points c-trib
    Mar 24, 2015 @ 18:52
    Chris Randle
    0

    PetaPoco connections best practice

    I'm currently connecting to the database using the following method:

    MyType myObject;
    using (var db = new Database("MyConnectionString"))
    {
        myObject= db.SingleById<MyType>(1234);
    }
    
    return myObject;
    

    All the examples are shown like this, including those used for the NPoco fork of PetaPoco examples. This is generally accepted as being the best practice approach. It certainly looks neat and tidy - more so than the other approach:

    var db = new Database("MyConnectionString");
    var myObject= db.SingleById<MyType>(1234);  
    db.Dispose();
    
    return myObject;
    

    However, according to Microsoft, this is bad. Why? Because if your code throws an exception before the closing bracket, the Dispose() method is not called (since this is the place where any remaining connections are closed) and I was wondering if someone could clarify what the best practice way is of using PetaPoco to ensure correct handling of the database connection? If for example I wrapped the above two examples in try - catch - finally blocks, with the second one I could at least dispose of the database for sure by manually calling the Dispose(). Thanks in advance!

  • Stephen 767 posts 2273 karma points c-trib
    Sep 07, 2016 @ 16:00
    Stephen
    1

    Re-read the MS docs carefully. In a using statement, the Dispose is in a finally block and is always called. So the first syntax is the preferred one, yes.

  • Nathan Rhodehouse 2 posts 72 karma points notactivated
    Jun 20, 2018 @ 18:57
    Nathan Rhodehouse
    0

    A quick look into the source code at https://github.com/CollaboratingPlatypus/PetaPoco/blob/development/PetaPoco/Database.cs shows that a using statement is already being implemented. There is no need to apply the using statement in your code.

  • pranjal 75 posts 188 karma points
    Jun 21, 2018 @ 13:38
    pranjal
    0

    Go to this site you will find complete information regarding how to use peta poco tables with Umbraco

    http://www.computermagic.gr/en-US/tutorials/umbraco-7/custom-tables-with-petapoco

Please Sign in or register to post replies

Write your reply to:

Draft