Brent
Brent

Reputation: 4876

The Model in MVVM architecture compared to MVC

I am trying to learn the MVVM pattern, and in particular what to do when a view represents a database table, but the view has a few elements representing a single database field. As a simple example:

Suppose I have a database field with a DateTime type (with a class having a property for each database field), but in the view, i have a datepicker for the date component and a TimeSpan for the time component.

In an MVC pattern, I would always have a POCO model which contained a nullable DateTime property for the datepicker and a nullable TimeSpan property for the time. I would map the database class across to the model.

In a MVVM pattern I can wrap the class representing the database fields, and have logic on the set accessors which keeps the wrapped class DateTime property in sync (and as the 2 fields are nullable, private DateTime and TimeSpan fields in the viewmodel, only setting the database class Datetime property if both date and time are not null)

Alternatively, I can have the viewmodel wrap a model much more like the MVC model - ie a POCO model with the date and time components representing seperate properties. The viewmodel then becomes a much simpler wrapper which implements INotifyPropertyChanged, along with a save ICommand which adds the date and timespan only as it creates or updates an instance of the database class.

Obviously both approaches "work", but what would be considered better practice and/or most adherent to MVVM architecture. Thank you.

Upvotes: 1

Views: 125

Answers (2)

Brent
Brent

Reputation: 4876

I ended up mapping and splitting the date from the database model to a mapped model, as it was better for validation messages to the user (the model implemented IDataErrorInfo). as I had a DateTime which needed to be before now, I could split the validation in the model into:

If date after today's date -> return string "Can't use a date later than today"

else if date present but time missing -> return string "Please enter the time"

else if DateTime after now ->return string "Can't be later than the current date and time"

the second approach would involve sharing simple, related validation logic between 2 classes which seemed silly.

Upvotes: 0

Palak.Maheria
Palak.Maheria

Reputation: 1515

When you implement INotifyPropertyChanged then events comes into picture and which is not advisable in MVVM because there may be scenario where your application faces issues with the controls updating its values on different threads.

It would be better if you use the first approach.

Upvotes: 1

Related Questions