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!
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.
PetaPoco connections best practice
I'm currently connecting to the database using the following method:
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:
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!
Re-read the MS docs carefully. In a
using
statement, theDispose
is in afinally
block and is always called. So the first syntax is the preferred one, yes.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.
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
is working on a reply...