0

I have just started a customer relation system and wanted to use MVVM design pattern in C#. But after some research, I get confuse with the view model and model. I am not sure where should I locate my code to access data from database. I believe that I have to add method (eg. GetCustomerById()) in view model and that method return a customer model back to view model but I am not sure about it.

Also, after searching on the internet all the MVVM pattern shows simple View-ViewModel-Models as the image below.

Original MVVM pattern

I was wondering, is it possible or correct for me to add a service layer or data access layer in between the view models and model like the screenshot shows?

MVVM pattern with Service Layer & Data Access Layer

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Most certainly. You can think of the model as a way to retrieve data that's outside of your UI. – Hayden Jun 08 '23 at 05:27
  • Can you please explain further? do you mean i need to put my DataAccess method in Models? Because, one of the article i read, says that Models is just a DTOs that only holds data so i am confuse. – Jayson Lim Jun 08 '23 at 05:37
  • The model in MVVM doesn't necessarily mean your traditional dto or poco. Think of model as a representation of your data outside of your UI. It can be a service layer, data access layer, or anything else. The important thing is how your view model transforms that model to suit the view. – Hayden Jun 08 '23 at 05:58
  • Thanks for explaining, Correct me if i am wrong. Say if i am dealing with Customers, I can have CustomerModel(Plain DTO), CustomerServiceModel(Methods to calculate customer rewards point or other), CustomerRepositoryModel (method to access customer data from db) all as a model. OR Just a simple CustomerModel (POCO, which combine all 3 Model into 1) and both works. Is that what you trying to say? @Hayden – Jayson Lim Jun 08 '23 at 06:10
  • You can take any approach you want. Your ViewModel can call out to your business logic or data access layer (the model) to perform some logic and return a response back to the view model. The view model will need to be able to interpret the response back to the view. – Hayden Jun 08 '23 at 06:19
  • I think I got what you mean. Thanks a lot for helping. – Jayson Lim Jun 08 '23 at 06:24

0 Answers0