msp1982dk
msp1982dk

Reputation: 93

Entity Framework - Should I call DbContext from BLL or DAL

I'm creating a WPF application which has the following layers:

UI (Views + ViewModels) -> BLL -> DAL

All of which reference the Domain Model layer.

At the moment I'm conveying all my DB calls from the UI to the DAL via the BLL. But I'm not sure this is the correct way.

Most of the methods in the BLL look like this:

public ICollection<User> GetUsers()
{
    return dbAccess.GetUsers();
}

Which in turn call a similar method in the DAL:

public ICollection<User> GetUsers()
{
    using (var context = new DbContext())
    {
        return context.Users.ToList();
    }
}

1) This way of conveying calls from BLL to DAL seems pretty redundant. Of course there are some BLL methods that actually holds a bit of business logic. Should I just ditch the BLL?

2) Another problem with this approach is that I can't use lazy loading because the DbContext is created and disposed in the DAL. I'm guessing this could be solved by creating the DbContext in the ViewModel, but when should I dispose it then?

3) Finally, as I'm not using lazy loading I have to eager load my related entities. But not all Views require the same related entities so I often end up with several methods that return the same entity but with different includes. It this ok?

X) All my DB methods exist in a single massive class called DbAccess. Would it be better to create a DB service class for each of my ViewModels (or perhaps each of my entities)?

Upvotes: 2

Views: 1365

Answers (1)

Janne Matikainen
Janne Matikainen

Reputation: 5121

You could call EF methods directly from the BL, but this would tie your BL to EF too tightly. If you write separate DAL to access EF then you can replace the entire DAL without touching BL, which would be impossible if you would call EF directly from BL.

You could also use DbContext for every httpRequest like so below

public static class ObjectContextPerHttpRequest
{
    public static MyEntities Context
    {
        get
        {
            string objectContextKey = HttpContext.Current.GetHashCode().ToString("ObjectContextPerHttpRequest");

            if (!HttpContext.Current.Items.Contains(objectContextKey))
            {
                HttpContext.Current.Items.Add(objectContextKey, new DomainModel.MyEntities());
            }

            return HttpContext.Current.Items[objectContextKey] as MyEntities;
        }
    }
}

Upvotes: 1

Related Questions