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)?