Maximc
Maximc

Reputation: 1762

Model with database in MVVM

Hello I am trying to learn MVVM, and I am kinda not certain about some parts, mainly the part where the (data)Model needs to communicate with the VM(ViewModel).

So I got a class person, it has lots of properties (with Raiseproperty(INotifyPropertyChanged)). Now how can I connect that class to to a VM I ll make a new class and call it ViewModelPerson, but I mainly want a list of Persons, since displaying only 1 person is kinda useless, the list will be gathered from a Database(SQLite) with Dapper. Now where do I need to create an observable list, in the viewmodel or in a (data)model? I think in the ViewModel, since I need to bind that to the View, but where do I insert the database info from it into the ViewModel ObservableCollection ? Do I put it in the constructor like ViewModelPersonsList Constructor that has a Query to gather all persons from a SQlite DB and insert it into the list ???

Hope you understand where I am failing to understand the MVVM model, if something is unclear please just ask, and I ll try to explain my question better.

Maxim

Upvotes: 6

Views: 3976

Answers (2)

Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104781

Since I see you mentioned Sqlite, I assume you're talking about small WPF projects.

I'd suggest you to make an entity framework code-first model mapped to your database (read this).

If you want to use SQL Server Compact Edition you can even have the database generated for you (well this can be achieved with Sqlite as well but with more effort).

Anyway, you then use the generated (or coded) DbContext as a UoW object.

You can choose to handle your data separately via a DAL or directly from the ViewModel.

Any case, I would say create two ViewModel base classes, one that exposes a TEntity, and the other that exposes a collection of TEntity. If you choose to do the DAL actions in your VM you can add CRUD methods onto your base CollectionViewModel and call then manually or let the user call it by exposing commands.

Upvotes: 1

Bob Horn
Bob Horn

Reputation: 34325

View -> View Model -> Business Logic -> Data Layer -> DB

OR

View -> View Model -> WCF/Web Service -> Business Logic -> Data Layer -> DB

If your view model needs a list of Person objects, then it should call your business logic layer, and your BLL will implement the necessary logic around calling the data layer. Your BLL returns the list, and your VM makes it available to the view via the binding.

Updating Person objects works the same way. The VM just calls the BLL with the updated objects.

Upvotes: 2

Related Questions