Refracted Paladin
Refracted Paladin

Reputation: 12216

Does my View Model have my Model and my Repository instance?

Hopefully I am being clear here. I have a ViewModel called A. I have a Model called M. I have a Repository for Model M and the DB stuff it maps to called RM.

Would my ViewModel, A, have a Property of my Model M AND my one for my Repository RM.

I would then use it by calling the various methods on RM and bind to M which I would pass to certain methods in RM like Save().

Make sense? Is that "normal" or even close?

Upvotes: 0

Views: 206

Answers (2)

MotoSV
MotoSV

Reputation: 2368

One approach would be to expose a property of type M, like you have at the moment, from the view model. The view will then bind to the properties of this exposed model. On your view model expose a method called Save and your view will call this method on the click of a button (binding can be used if you're using WPF). The Save method will then create an instance of the repository, add the property of type M to it and then save the repository.

Example:

public class ViewModel
{
  public void Save()
  {
    // Create your repository
    // Add this.Model to the repository
    // Save the repository changes
  }
  public M Model { get; set; } // Bind your view to this.
}

This allows you to perform other operations before and after the save, you can use other properties to decide if, and what you save, and how your view model "saves" remains part of the view model and not the repository.

I would also recommend looking into using dependency injection, as mentioned by @devdigital, for your repository. This would mean you wouldn't have to create your repository in your Save method and instead you would use the instance of the repository passed into the constructor of the view model.

Upvotes: 0

devdigital
devdigital

Reputation: 34369

You could be describing a typical situation, depending on your preferences. If your view model wishes to work with entities, then it could do so via a repository which you could inject as a dependency using constructor injection, and your view model could work against an abstraction rather than a specific implementation of your repository.

If you wished to access the repository at a later point after construction, then you could assign the repository to a private field or property for example.

In terms of your model, you could have a property which exposes this to the view so that you didn't need to duplicate the properties of the model on your view model. However, this would depend on whether you are happy with the view having direct access to your model which could be a violation of the LoD (Law of Demeter) in order not to violate the DRY (Don't Repeat Yourself) principle.

Upvotes: 1

Related Questions