Search code examples
disposewebmatrix

WebMatrix Database.Open... Close() and Dispose()


Anytime I read about Close() and Dispose(), I end up seeing lot of references to just use the Using Block but I have yet to find how to use a Using Block in WebMatrix C# Razor Syntax.

So I don't want an answer that says just use a Using Block, unless you can tell me exactly how with example.

Specific to use of Database.Open(), after I am done with my connection/queries

My questions are:

  • Should I use both Close() and Dispose()?
  • Does it matter whether I call Close() and then Dispose() or Dispose() and then Close()?

Hoping for simple answers to simple questions. Thanks


Solution

  • ASP.NET Web Pages framework examples of the Database helper do not include calls to Close or Dispose because the framework itself is designed to call Dispose for you at the end of a request. If you use ADO.NET instead of the Database helper, you should employ using statements. Having said that, there is nothing to stop you from wrapping Database helper calls in using blocks:

    IEnumerable<dynamic> floaters = null;
    using(var db = Database.Open("MyDb")){
        var sql = "SELECT * From LifeRafts";
        floaters = db.Query(sql);
    }
    

    If you wanted to manage it all yourself, you can simply call Close or Dispose. They both result in the connection being returned to the ADO.NET connection pool anyway.