Confused with Model vs ViewModel - c#

I am Learning ASP.NET MVC and downloaded a couple of sample apps. MusicStore etc...
I am coming from a wpf background where we had the MVVM Pattern.
I have noticed that they used the concept of model and ViewModel.
In MVVM is pretty clear that you bind the view to the ViewModel injecting the model into the viewModel.
In MVC you have a controller but I am not sure and confused how the all ties together,as I cannot see the model injected into the ViewModel
I have the following structure
MyCompany.Entities.dll (All the models go here) EG Product
MyCompany.Dal.dll (All the repositories go here)
MyCompany.Services.dll (called by MyCompany.WebUI.Controller calls MyCompany.Dal)
MyCompany.WebUI.MyApp
MyCompany.Tests
From some of the examples I have seen your Model acts as a ViewModel.Am I correct?
Let's take a controller i have something like
public class ProductController
{
public ProductController(IProductRepository productRepository)
{
//omitted as not relevant
}
}
public class ProductVM
{
public ProductVM()
{
// Shouldn't we inject the model here RG Product
}
}
Is there some N-tier examples out there I can refer to?
Is the concept of ViewModel a valid one in MVC?
What is the standard?
Thanks for any suggestions.

Use ViewModels to simplify the View.
For instance, you might have a deep object graph with Products, Order, Customers, etc - and some information from each of these objects are required on a particular View.
A ViewModel provides a way to aggregate the information required for a View into a single object.
ViewModels also allow for things like data annotations and validation - which does not belong on your model, as your model should stay "domain-specific".
But in reality, ViewModels are nothing more than a simple wrapper for your domain objects.
Use a tool like AutoMapper to map back and forth between your ViewModels and domain models with ease.
Personally I always bind to ViewModels in my Views, never to the domain models, even if it's a single object. Why? Well I like to decorate my ViewModels with UIHints, validation, data annotations. Just the same way your domain models are enriched with domain-specific rules and business logic, so should your ViewModels be enriched with UI-specific logic.
If you simply have a object with a 1-1 representation of your domain model, you are missing the point of ViewModels.
Add to the ViewModels only, and nothing more, what is required for a particular View.
Example controller action
public ActionResult CustomerInfo(int customerId)
{
// Fetch the customer from the Repository.
var customer = _repository.FindById(customerId);
// Map domain to ViewModel.
var model = Mapper.Map<Customer,CustomerViewModel>(customer);
// Return strongly-typed view.
return View(model);
}

The difference between MVC and MVVM is that MVC has one set of classes for the data entities. In MVVM you have 2 - one set for binding to your views, and one set for managing the data persistence (which could be in a separate WCF service for example).
The benefits of MVVM are that the model bound to the views is relevant to the UI and completely independant from the persistence Model.
Which to use? Well it depends on how closely the data structure required by your Views maps to the structure of the database. When it is similar - it is possible to bind the DataEntities from your DAL directly to your view - this is the classic MVC pattern. However, you gain much with a separate ViewModel as you can extend these classes with View specific behaviour (e.g. Validation) that your DAL should not be concerned with.
For all but the most simple applications, I would recommend use of a separate ViewModel.

Extremely simple,
ViewModel can be the combination of multiple Model classes, to display or transforming the data to and from within the Network, may be via API calls.
However, Model class is nothing but just be specific to any particular entity, Object or strict to a particular Table.
Ex- For "EmployeeViewModel" can be the combinations of Multiple Model Classes i.e. EmpBasicDetails + EmpAddressDetails +EmpExperienceSummary.
Whereas, "EmpBasicDetails" - is specific Model class which contains the Employee Details specifically.
~Cheers,

Related

Business Logic when Model (Parent) contains a collection of Polymorphic Models (Children)

In MVVM architectures, specifically the Model layer; when a Collection<BasicModelType> is used full of objects that inherit/implement BasicModelType; how does one go about handling any business logic on the "Models" in the collection without having to implement a portion of the business logic in the "Models" themselves? (Assumption "as" and "is" usage is not allowed as it is poor OOP practice).
---Further Explanation below if above is not totally clear.---
"Model" means a basic class with just properties.
ViewModel gets the Model via a XMLService.
XMLService is just a class that knows how to create Models from what is in the XML document. (This is just to tell how the models got created)
OutputService is a class that knows how to use the Models to create an Output from the software based on what is in the Models. It also has other logic outside of what it needs to do with just the Models.
The Model includes a Collection of other ChildrenModels. The ChildrenModels are polymorphic in that they come from a BaseModel. Having a BaseModel is desirable as it allows them to be stored and presented to the user as a contiguous collection. Example below, apologies, as it is the simplest example I could think of.
Truck : Vehicle
Name
HasTrailer
Car : Vehicle
Name
HasSpoiler
The Logic defined in the OutputService would need to do different things depending on if the ChildModel in a given Model's Collection is a Truck or a Car. The issue is that of course, the ChildCollection is of the base class type Vehicle. The only time the actual type is known is during instantiation of the ChildModel object (and it is known because the type in the XML is specific).
Is there a common pattern to handle how the OutputService would apply any of its functionality to the ChildModel collection. It by definition would need to know each models type.
It seems COMPLETELY wrong to have switch statements checking the type (with as or is).
Of course a solution would be to include the logic from the "OutputService" in the actual ChildModel; just exposing the function that executed that logic in the BaseClass or an Interface. Then any object/service/veiwmodel could just iterate through the list calling said functions getting the Model specific results. But doesn't this essentially split the Business Logic up? Hasn't the "concerns" been sprinkled everywhere?
If you read The MVVM Pattern.
View
The view is responsible for defining the structure, layout, and
appearance of what the user sees on the screen. Ideally, the view is
defined purely with XAML, with a limited code-behind that does not
contain business logic.
Model
The model in MVVM is an implementation of the application's domain
model that includes a data model along with business and validation
logic. Examples of model objects include repositories, business
objects, data transfer objects (DTOs), Plain Old CLR Objects (POCOs),
and generated entity and proxy objects.
View Model
The view model acts as an intermediary between the view and the model,
and is responsible for handling the view logic. Typically, the view
model interacts with the model by invoking methods in the model
classes. The view model then provides data from the model in a form
that the view can easily use. The view model retrieves data from the
model and then makes the data available to the view, and may reformat
the data in some way that makes it simpler for the view to handle. The
view model also provides implementations of commands that a user of
the application initiates in the view. For example, when a user clicks
a button in the UI, that action can trigger a command in the view
model. The view model may also be responsible for defining logical
state changes that affect some aspect of the display in the view, such
as an indication that some operation is pending.
So from this we can see that you should split the business logic up using the child classes. Abstract the logic of creating an output depending on the child. If you have doubts in your OOP design, think of which is more maintainable. See SOLID (object-oriented design).

What's the point of having models in WPF?

So far I have yet to see the value of having models in WPF. All my ViewModels, by convention, have an associated Model. Each of these Models is a virtual clone of the their respective ViewModel. Both the ViewModel and Model classes implement INotifyPropertyChanged and the ViewModel just delegates everything to the Model anyway.
Why bother having Models then? Why can't I just move my Model logic up into the ViewModel and call it a day?
It seems rather redundant (that is, not DRY) to have MVVM, and just use VVM by default unless some special edge case demands a Model.
If using explicit model classes better supports unit testing, for example, or some other best practice, I can see the value.
The model is just the low level application data.
The view model is more specific.
It's like a window tapping into the data tailored for the view.
It also augments the model with details needed for the view. A good example is pagination.
A model can have more than one view model. These view models would offer different aspects of the data.
You can create a mashup of different data sources. A view model cleanly façades the models involved.
That means there is no 1:1 relationship between models and view models.
So, if you just display the low level data without a lot of additional logic, features, summaries, aggregations, filters, etc. you can do away with view models and just use the model directly. This seems to be the case with your project.
The model can be auto-generated (Entity Framework), or it might not be a specific class at all (think of a DataTable).
I assume that if you say "I don't use a model", you do in fact use a model, you just don't call it that way.
First of all, even in MVVM you can expose your Model directly in the VM and bind through it to the Model. {Binding MyModel.MyModelsProperty} where DataContext = ViewModel that way you don't have to necessarily wrap everything unless that is just your style to do so.
The ViewModel and Model have different responsibilities. For example, consider designing a file explorer with a tree view of folders. Each node in the tree view is a Directory/Folder. The directories are the models and they have properties related to the file system. The ViewModel may wrap or expose these properties for the TreeView nodes to display (For example the Name of the directory), but it also adds additional information such as "IsEditing" and "IsExpanded" to determine the state that the node is in.
You're just talking about one pattern in MVVM, actually there are more.
In Stateful viewmodel you don't actually delegate things to Models, Viewmodel itself maintains its state, so as you said in this pattern you can almost ignore the model as you can have state in VM itself.
To create isolation between business logic and presentation, data
should be removed from the view. The stateful view model pattern moves
data into the view model using XAML data binding. This allows the view
model to be tested without constructing a view, and it allows the view
to change with minimal impact on the business logic.
In Stateless viewmodel you delegate the calls to Model, which is what you're probably referring to.
Note that you don't necessarily implement INotifyPropertyChanged in Model. Just implementing it in VM is fine as long as you don't change the properties directly in Model.
So why do we need VM and Model? VM is for supporting view like providing Commands, etc and Model is just to hold the piece of data abstract the same.
If you think of it as an abstraction, let's say you need to build a screen to display a list of Employees and make a Selection, Search or Filter. Then we break it up in components. You will require:
An Employee class (Model)
An EmployeeManagementViewModel to prepare and present your list of Employees and manage state changes for your View (e.g. can contain a SelectedEmployee, Filter Search text, etc) to be used by your EmployeeManagementView
A list of Employees (Which will live in your EmployeeManagementViewModel)
Most likely you will already have an Employee class. If that's the case then you just need to expose that model in your EmployeeManagementViewModel as an ObservableCollection of Employees.
In case you don't already have an Employee class you may decide to create an EmployeeViewModel and add your Employee properties there like FirstName, LastName, etc.
Technically this will work but conceptually it bothers me because an EmployeeViewModel is not an Employee (it contains an employee). If you're abstracting reality then, the blueprint of an Employee should not include properties or methods to be used by a View. To me Employee should be a POCO which could implement INotifyPropertyChanged and nothing more than that. You're separating View state from the Model itself. Having an Employee POCO makes it easier to UnitTest, create mock employees, map it to a database table through an ORM, etc.
As the name implies the ViewModel is the model for your View and the Model is the model for your business domain
Anyway that's how I see it. When I started doing MVVM work I had that same question but over the years seems like it makes sense.
In general, my Models end up being a Data Access Layer, be it through Entity Framework, a WCF proxy, or some other class.
Depending on concurrency issues, the class could be static or instanced. If you can separate the behavior enough, you could "split" the DAL classes into a separate model for each view model, but duplicate code could become a problem.
Wikipedia: MVVM
Model: as in the classic MVC pattern, the model refers to either (a) a domain model which represents the real state content (an object-oriented approach), or (b) the data access layer that represents that content (a data-centric approach).
Your ViewModel isn't a substitute for your domain Model. It acts as an intermidiate between your view and the model, including commands, binding collections to your view, validation, etc.
Your domain model should also be reusable across ViewModels. If you implement it all in the VM you will end up abusing the DRY principle by sharing specific VM logic across multiple VMs.
In my experience when you just use Domain models as the ViewModel (as a property of the VM) you end up with a lot of Keys that require you to either go get the text value and store somewhere else or you end up adding the property to the VM anyway. Your view typically has more info than just one single domain model (e.g. related objects, display values, text status values etc..), something that the Domain model has no need for and would ultimately weigh it down. The view model is dedicated to the needs of the view, it keeps coding the View simple and non-complex.

How should I be binding my business models to my views?

I've come across an interesting question during my development. Right now, I use a database-agnostic unit of work layer to abstract the access of data from the actual database dependencies in my ASP MVC 4 web application.
Each individual database project which implements the unit of work interfaces are aware of my business models (models that go directly to/from the database). I'm not too sure how I feel about this approach, but that's not the question I am going to ask.
Should I be using a solution like AutoMapper to convert my business models to/from domain models - models that are passed to the view and used for any work that shouldn't have access to database fields (i.e., IDs)?
For example, consider inside my BusinessModels project, I have the following classes
BusinessModels
/UserAccounts/
User.cs
- ID
- Username
- HashedPassword
- Salt
UserSettings.cs
- IsSubscribedToNewsletter
- AllowDirectEmails
Would it make any sense to bind these User, and UserSettings models into a single model using AutoMapper like so
MyProject
/DomainModels/
User.cs
- Username
- HashedPassword
- Salt
- IsSubscribedToNewsletter
- AllowDirectEmails
for the purpose of views?
This question also extends to non-MVC projects but I feel seeing as I am working on an MVC project it would make more sense to ask it in that tag.
TLDR is there any point in mapping business models/entities to view models or does that provide an unnecessary layer of abstraction? And if so, would the Repositories contain business models, or view models (which map automatically to business models under-the-hood)?
You can use view models for two different things:
rendering a new view (GET action), passing the view model object as the model for the view
receiving data back from the view, in a Post Action (POST action), using the view model as parameter
(I know, the second is arguable. But it's not strange to use the view models for this)
The model for the GET action needs all the properties neccessary to render the View:
the values of the entity you're showing/editing
extra values needed to render the view (for example SelectLists for drop down lists)
Suppose that you have a User which can belong to one UserGroup.
In this case, if you want to edit the user, the model needs:
the User data
a list of UserGroups
I'd use a model like this:
public class EditUserModel
{
public User User {get;set;}
public SelectList UserGroups {get;set;}
}
As you can see, I directly add the User as a property. But I don't add the list of categories as a property, because I don't need the whole list of categories, with all their properties in the view. Besides, if you unit test the controller you can verify that the SelectList is as expected (that couldn't be done if you created the User Groups list in the view)
But, what if you don't need all the properties of the user in the View? Is it worth removing the User property, and add individual properties for Name, Email, JoinedData, Active... ? I think the anser is NO. Imagine you add/remove or rename some of the User entity properties. If you had individual properties in the view model, you'd have to change them as well, before updating the View. And, if you rely on automatic mapping (auto mapper, value injecter) you would't even realized if you make some mistake.
I also said that the view model can be used for posting back data to the controller. So you could do this:
[HttpPost]
public ActionResult Edit(EditUserModel userModel)
If you do so, the model binder will populate the userModel with the values in the form controls. So you'lll get back a half empty model. In this case, the UserGroups list would be null, and, depending on how many of the User's properties you edit, the User could also have many null/non-initialized properties.
To avoid making errors, in some occasions is advisable to create a different model (and probably auxiliary classes) to make it clear what is expected to be posted to the model.
For example, if you have an action to show the whole user data, but which only allows to change its password, you could create a class with two properties: Password, and PasswordConfirmation.
In this case, the view model for the POST could only have the Password and PasswordConfirmation. And derive a model for the GET which has this inherited properties, and also the list of User Groups and the User.
Why inheriting and not using independent classes? Simply beacuse when you use something like Html.TextBoxFor(m => m.User.Name), the Model Binder will be able to set the Name property of the User property, only if the parameter for the post action has the same structure. I.e. if the view model for the get has this structure:
public ChangePasswordModel
{
public string Password {get;set;}
public string PasswordConfirmation {get;set;}
// extra properties, like the list of user groups, the user data...
}
And the model for the post has this structure:
public PostedChanegPasswordModel
{
public User User {get;set;}
}
The content of the input rendered by Html.TextBoxFor(m => m.EditedUser.Name) won't be bound to the User.Name of the PostedEditViewModel.
But if you make this:
public EditUserModel : PostedEditUserModel
{
// extra properties, like the list of user groups
}
the data will be bound without any problem.
In general you have to be careful with the models you use for posting and getting. And I recommend using as many different view models as neccesary.
When to use automatic property mapping to completely new view and different models?
You must have a very strong reason to have different view models. This could be a result of starting the application from outside in (i.e. design first) or because a team is developing the UI before or while the business logie is being implemented.
In this case you can find that the classes for the view models, and the views themselves are already defined, and are quite similart to your entities, but not exactly equal. This is one case when I think it can be good to use mappers.
The other reason to use different classes would be to decouple the interface from the logic. But this usually only happens in the previous case.
Regards viewmodels I treat them like a summary of the data you wish to work with.
So taking from your example, your viewmodel would contain data from both the User and UserSettings classes. Let's say you had a view named UserData.cshtml then I would code it up like so:
public class UserDataViewModel
{
public string Username { get; set; }
public bool AllowDirectEmails { get; set; }
// etc ...
}
public ActionResult UserData()
{
var viewModel = new UserDataViewModel();
viewModel.UserName = "Whatever";
viewModel.AllowDirectEmails = false;
// Or however you get the data for the user.....
return View(viewModel)
}
Hopefully you get the idea. So you are on the right track with merging information from externals classes into one viewmodel class. Bascially tie everything together in the viewmodel class.
I name the viewmodel class the same as the view that it's going to be used for. This can help documentation, as well as make it easier for devs new to the code to follow.

ASP.NET MVC Design Issues

Whats the difference between Model and ViewModel? I should use both of them or I better skip one of them? who grabs the data from the database?
I wonder whats the best/right way to take my data from the database.
One option is to have a DAL (Data Access Layer) and instantiate it in every controller,
fill with it the viewmodels like:
var viewmodel = Dal.GetArticles();
Another option is to let the model itself grab the information from the Database:
var model = new ArticlesModel();
model.GetArticles();
public void GetArticles()
{
var context = new DbContext();
_articles = context.Articles
}
Another similar option is to have a static DAL so you can access it inside every model,
so each model will have a method to grab the data using the static DAL class (Which contain a DbContext class inside to access the Database)
public void GetArticles()
{
_articles = DAL.GetArticles();
}
So the general question is if the model itself needs to grab the data from the database or the controller itself can have access to the DAL.
While someone is writing a more useful answer, I will quickly address your points.
Model is the data you want to display.
More often than not, you will want to use object relational mapping so most of your business object classes correspond to database tables and you don't have to manually construct queries.
There are plenty of ORM solutions available, including Entity Framework, NHibernate and (now dying) LINQ to SQL.
There is also an awesome micro-ORM called Dapper which you may like if bigger frameworks feel unneccessarily bloated for your solution.
Make sure you learn about the differences between them.
DAL is more idiomatic in .NET than classes that “know” how to load themselves.
(Although in practice your solution will very likely be a mixture of both approaches—the key is, as usual, to keep the balance.)
My advice is to try keeping your models plain old CLR objects as long as your ORM allows it and as long as this doesn't add extra level of complexity to the calling code.
These objects, whenever possible (and sensible—there are exceptions for any rule!), should not be tied to a particular database or ORM implementation.
Migrating your code to another ORM, if needed, will be just a matter of rewriting data access layer.
You should understand, however, that this is not the main reason to separate DAL.
It is highly unlikely you'll want to change an ORM in the middle of the project, unless your initial choice was really unfit for the purpose or you suddenly gained a traction of 100,000 of users and your ORM can't handle it. Optimizing for this in the beginning is downright stupid because it distracts you from creating a great product capable of attracting even a fraction of hits you're optimizing for. (Disclaimer: I've walked this path before.)
Rather, the benefit of DAL is that you database access becomes always explicit and constrained to certain places where you want it to happen. For example, a view that received a model object to display will not be tempted to load something from the database, because in fact it is the job of controller to do so.
It's also generally good to separate things like business logic, presentation logic and database logic. Too often it results in better, less bug-ridden code. Also: you are likely to find it difficult to unit-test any code that relies on objects being loaded from the database. On the other hand, creating a “fake” in-memory data access layer is trivial with LINQ.
Please keep in mind that again, there are exceptions to this rule, like lazy properties generated by many ORMs that will load the associated objects on the go—even if called within a view. So what matters is you should make an informed decision when to allow data access and why. Syntaxic sugar might be useful but if your team has no idea about performance implications of loading 20,000 objects from ORM, it will become a problem.
Before using any ORM, learn how it works under the hood.
Choosing between Active Record-style objects and a DAL is mostly a matter of taste, common idioms in .NET, team habits and the possibility that DAL might eventually have to get replaced.
Finally, ViewModels are a different kind of beast.
Try to think of them like this:
You shouldn't have any logic in views that is more sophisticated than an if-then-else.
However, there often is some sophisticated logic in showing things.
Think pagination, sorting, combining different models in one view, understanding UI state.
These are the kinds of thing a view model could handle.
In simple cases, it just combines several different models into one “view-model”:
class AddOrderViewModel {
// So the user knows what is already ordered
public IEnumerable<Order> PreviousOrders { get; set; }
// Object being added (keeping a reference in case of validation errors)
public Order CurrentOrder { get; set; }
}
Models are just data, controllers combine the data and introduce some logic to describe data to be shown in view models, and views just render view models.
View model also serves as a kind of documentation. They answer two questions:
What data can I use in a view?
What data should I prepare in controller?
Instead of passing objects into ViewData and remembering their names and types, use generic views and put stuff in ViewModel's properties, which are statically typed and available with IntelliSense.
Also, you'll likely find it useful to create ViewModel hierarchies (but don't take it to extremes!). For example, if your site-wide navigation changes from breadcrumbs to something else, it's cool to just replace a property on base view model, a partial view to display it and the logic to construct it in the base controller. Keep it sensible.
A model represents the structure you like your data in and is not concerned about the view which may consume it. A model's intend is purely that of representing the structure.
A model may contain properties irrelevant to the view consuming it.
A view-model is designed with the view in mind. A view-model is intended for a 1-to-1 relationship to a view. A view-model only contains the basic fields and properties the view it is intended for requires.
In general you would have your controller contact a repository (In your example your DAL) obtaining the data and then populating either a model or view-model with the results, sending it down to the view.
Model (Domain Model): is the heart of the application, representing the biggest and most important business asset because it captures all the complex business entities, their relationships and their functionality.
ViewModel: Sitting atop the Model is the ViewModel:The two primary goals of the ViewModel are
1. to make the Model easily consumable by the View and
2. to separate and encapsulate the Model from the View.
Eg.
Model:
public class Product
{
...............
}
public class Category
{
...........
}
ViewModel:
public class ProductViewModel
{
public ProductViewModel(List<Product> products, List<Category> categories)
{
this.Products = products;
this.Categories = categories;
}
public List<Product> Products { get; set; }
public List<Category> Categories { get; set; }
}

MVVM where to put Data Access Layer?

I am investigating WPF's MVVM design pattern. But am unsure where to put the Data Acess code?
In some examples I have looked at, data access is performed directly in the ViewModel. It seems odd to put something like linq to sql in the ViewModel? Other examples have a seperate project for Data Access, this seems more like it?
Is this there a general approach? I feel like I am missing something here!
Thanks
Here's how I've been organizing my MVVM w/ LINQ projects:
Model - I think of the Model as the state of the system. It provides an interface to the data, and it keeps track of system status. The Model does not know about the ViewModel or View--it just provides a public interface to its data and various events to let the consumers (usually ViewModels) know when the state has changed.
ViewModel - The ViewModel is in charge of organizing or structuring all the data needed by the View, keeping track of the status of the view (such as the currently selected row of a data grid), and responding to actions on the view (such as button pushes). It knows what the view needs, but it doesn't actually know about the view.
View - The View is the actual look and feel of the UI. It contains all the built-in and custom controls, how they arranged, and how they are styled. It knows about the ViewModel, but only for the purpose of binding to its properties.
Gateway - This is the part that directly addresses your question. The Gateway (which is basically my way of saying "DataAccessLayer") is its own separate layer. It contains all the code (including LINQ queries) to CRUD or select, insert, update, and delete data from/to your data source (database, XML file, etc.). It also provides a public interface to the Model, allowing the Model to focus on maintaining system state without having to concern itself with the details (i.e., the queries) needed to update the data source.
DataAccess Classes - In C#, these are very simple classes that model your elemental data objects. When you select something using a LINQ query, you will usually create an IEnumerable<T> or List<T> where T is one of your data objects. An example of a data object would be:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
The big advantage of a design like this is that it really separates your concerns. Everything has a specialized job, and it's (usually) pretty easy to know what kind of thing goes where.
The disadvantage is that it may be overkill for small projects. You end up creating a lot of infrastructure for public interfaces that basically pass a single wish through several layers. So, you might end up with a scenario like this: [user clicks Submit, ViewModel tells Model to AddNewPerson, Model tells Gateway to InsertPerson] instead of a scenario like this [user clicks Submit, ViewModel adds new record to the database directly].
Hope that helps.
I would add another layer, essentially what you want is a data factory. You want to create a set of classes that will CRUD to the database for you and return clean POCO objects to the ViewModel.
A good example to look at would the Nerd Dinner book. It covers MVC not MVVM but the patterns are very similar and the way they access data in that solution would be good starting point.
Hope this helps.
Data access should not be in the view model, as this is supposed to be a view specific (possibly simplified) representation of the domain model.
Use a mapper of some sort to map your view model (the VM in MVVM) to your model (the first M). New objects in your model can be created using the factory pattern. Once created, you can store them in a database using the repository pattern. The repositories would then represent your data access layer. In your repository you could use an O/R mapper like NHibernate or Entity Framework.
EDIT:
I see that GraemeF suggests putting the data access code in the model. This is a NOT a good approach, as this would force you to update your domain model if you were to move from e.g. SQL Server to Oracle or XML files. The domain objects should not have to worry about how they are persisted. The repository pattern isolates the domain from its persistence.
MVVM stands for Model, View, and ViewModel. The piece you are missing is the Model, which is where your data access code lives.
The ViewModel takes the Model and presents it to the View for display, so typically you would have something like this:
class PersonModel : IPerson
{
// data access stuff goes in here
public string Name { get; set; }
}
class PersonViewModel
{
IPerson _person;
public PersonViewModel(IPerson person)
{
_person = person;
}
public Name
{
get { return _person.Name; }
set { _person.Name = value; }
}
}
The PersonView would then bind to the properties of the PersonViewModel rather than directly to the model itself. In many cases you might already have a data access layer that knows nothing about MVVM (and nor should it) but you can still build ViewModels to present it to the view.
Your ViewModel should be a thin layer that just services the view. My rule of thumb: if it has to do with the presentation of the UI, then it belongs in the ViewModel, otherwise it should be in the Model.
The WPF Application Framework (WAF) contains a sample application that shows how the Model-View-ViewModel (MVVM) pattern might be used in combination with the Entity Framework.

Categories

Resources