Copied to clipboard

Flag this post as spam?

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


  • Bjarni Egill 3 posts 72 karma points
    Jul 26, 2018 @ 17:08
    Bjarni Egill
    0

    Guidance to proper use of Umbraco.Core.Persistence.Database

    I have been running into the dreaded There is already an open DataReader associated with this Command which must be closed first error, and it got me questioning how we are using the Database() class.

    Here is a very generic example of how it has been used:

    var connectionString = "umbracoDbDSN";
    var db = new Database(connectionString);
    var repo1 = new Repo1(db);
    var repo2 = new Repo2(db);
    
    repo1.SomeQuery();
    repo2.SomeOtherQuery();
    

    Basically reuse the context(Is it the correct word for it?) between repos.

    Then I stumbled across this article when reading this stackoverflow post which basically says that you should be creating a new context for each query.

    Which I would roughly interpret as such:

    public class Repo1
    {
        private string _connectionString;
    
        public class Repo1(string connectionString)
        {
            _connectionString = connectionString;
        }
    
        public string SomeQuery()
        {
            string result = null;
            using(var db = new Database(_connectionString))
            {
                result = db.SingleOrDefault("SELECT TOP 1 CustomerName FROM Customers")
            }
            return result;
        }
    }
    

    Now I don't know if this approach applies to the Database class since I am not familiar with how it works. So can anyone tell me which one is the proper implementation or preferably point to a third if both are incorrect?

  • Dan Diplo 1554 posts 6205 karma points MVP 5x c-trib
    Jul 26, 2018 @ 18:40
    Dan Diplo
    0

    If your using the current Umbraco database you don't need to create an instance of it, you can access it via the ApplicationContext eg.

    var db = ApplicationContext.DatabaseContext.Database
    

    You can then pass this instance to your repos.

  • Bjarni Egill 3 posts 72 karma points
    Aug 01, 2018 @ 09:30
    Bjarni Egill
    0

    Isn't that the same as passing new Database to the repos? I am just wondering what the difference is.

Please Sign in or register to post replies

Write your reply to:

Draft