0

I'm currently writing my first MVVM application which uses EntityFramework for data access. The Application relies heavly on the underlying database and has to add new Data to the DB in many cases.

However, I'm uncertain about whether or not it is a good idea to call the ObjectContext inside the ViewModel. e.g.

public class SomeViewModel : ViewModelBase
{
    public IEnumerable<User> AllUsers { get; private set; }

    private void SomeMethod()
    {
        var __entities = new DatabaseEntities();
        AllUsers = __entities.Users.Where(...).ToList();
    }

}

I've seen solutions like this, but there are some question coming along with it. For example how long the ObjectContext actually lives, or if one should prefer a single, global accessable ObjectContext.

Or should calls like those not be part of the VM in the first place? Currently I can also imagine to implement like StaticHelpers for each DB table and use Methods like GetAllUsers().

In Josh Smith's sample Application about MVVM he uses a Repository thats injected in the Constructor of each VM.

public AllCustomersViewModel(CustomerRepository customerRepository)

Despite the fact that this has to be a common issue, I found no satisfying answer on how this issue is approached for smaller applications (best practice)?

  • I think calling the ObjectContect directly from a method in your viewmodel means that if you don't have a nice GetAllUsers() method that can be accessed by a different viewmodel(if necessary). If you don't have such a requirement, then I think it's quite alright. You could wrap your DatabaseEntities instantiation in a using. I think the problem you will face with your current workflow is managing UI updates. First, you are using IEnumerable instead of ObservableCollection, second, you are using the EF User class directly instead of wrapping it in a VM that implements INPC. – failedprogramming Mar 27 '13 at 00:16

1 Answers1

2

In the descripton of the DbContext class on MSDN it states "Represents a combination of the Unit-Of-Work and Repository patterns", so it can act as your Repository layer, although it doesn't have to, and it is intended to be used for a "Unit of Work" which doesn't fit using a global one for the entire app. Besides keeping a single one around for everything could cause issues with cached data and other undesirable things (memory usage, etc...).

Hope this helps.

Brent Stewart
  • 1,830
  • 14
  • 21