ViewModel -> Model: Who's responsible for persistance logic? - asp.net-mvc-2

in my ASP MVC 2 application I follow the strongly typed view pattern with specific viewmodels.
Im my application viewmodels are responsible for converting between models and viewmodels. My viewmodels I have a static ToViewModel(...) function which creates a new viewmodel for the corresponding model. So far I'm fine with that.
When want I edit a model, I send the created viewmodel over the wire and apply the changes to back to the model. For this purpose I use a static ToModel(...) method (also declared in the view model). Here the stubs for clarification:
public class UserViewModel
{
...
public static void ToViewModel(User user, UserViewModel userViewModel)
{
...
}
public static void toModel(User user, UserViewModel userViewModel)
{
???
}
}
So, now my "Problem":
Some models are complex (more than just strings, ints,...). So persistence logic has to be put somewhere.(With persistence logic I mean the decisions wheater to create a new DB entry or not,... not just rough CRUD - I use repositories for that)
I don't think it's a good idea to put it in my repositories, as repositories (in my understanding) should not be concerned with something that comes from the view.I thought about putting it in the ToModel(...) method but I'm not sure if thats the right approach.
Can you give me a hint?
Lg
warappa

Warappa - we use both a repository pattern and viewmodels as well.
However, we have two additonal layers:
service
task
The service layer deals with stuff like persisting relational data (complex object models) etc. The task layer deals with fancy linq correlations of the data and any extra manipulation that's required in order to present the correct data to the viewmodel.
Outwith the scope of this, we also have a 'filters' class per entity. This allows us to target extension methods per class where required.
simples... :)

In our MVC projects we have a seperate location for Converters.
We have two types of converter, an IConverter and an ITwoWayConverter (a bit more too it than that but I'm keeping it simple).
The ITwoWayConverter contains two primary methods ConvertTo and ConvertFrom which contain the logic for converting a model to a view model and visa versa.
This way you can create specific converts for switching between types such as:
public class ProductToProductViewModelConverter : ITwoWayConverter<Product,ProductViewModel>
We then inject the relevant converters into our controller as needed.
This means that your conversion from one type to another is not limited by a single converter (stored inside the model or wherever).

Related

Entity Framework & WPF Application Design Guidance

Entity Framework Layer Guidance
I'm in the design stage of a WPF business application. The first stage of this application will be a WPF/Desktop application. Later iterations may include a browser based mini version.
I envision creating a dll or 2 that contain the domain model & dbcontext that all applications(Desktop or Browser) will use.
My intention is to ride or die with EF. I'm not worried about using DI/Repository patterns etc for flexibility. The benefits of using them don't outweigh the added complexity in my opinion for this project. My plan is to use a model, and a derived dbcontext.
Having said that, I'm looking for input on where to put certain types of method code.
An example will hopefully make my question more clear:
Let's say I have the following two entities..
Entity: Employee
Entity: PermissionToken
Inside of these two entities I have a ManyToMany relationship resulting in me creating another entity for the relationship:
EmployeesPermissionTokens
For clarity, the PermissionToken Entity's Primary Key is an Enum representing the permission..
In the application, lets say the current user is Administering Employees and wants to grant a permission to an Employee.
In the app, I could certainly code this as:
var e = dbcontext.Employees.Find(1);
var pt = new PermissionToken
{
PermissionID=PermissionTypeEnum.DELETEUSER";
...
}
e.PermissionTokens.Add(pt)
But it seems to me that it would be more convenient to wrap that code in a method so that one line of code could perform those actions from whatever application chooses to do so. Where would a method like that live in all of this?
I've thought about adding a static method to the EF Entity:
In The employee class:
public static void GrantPermission(PermissionToken token)
{
e.PermissionTokens.Add(token);
}
Going further, what would be really convenient for the app would be the ability to write a line like this:
Permissions.GrantToEmployee(EmployeeID employeeId, PermissionTypeEnum
permissionId);
Of course that means that the method would have to be able to access the DbContext to grab the Employee Object and the PermissionObject by ID to do its work. I really want to avoid my entities knowing about/calling DbContext because I feel long term the entities get stuffed full of dbcontext code which in my opinion shouldn't even be in the Model classes.
So Where would a method like this go?
My gut tells me to put these sorts of code in my derived DbContext since in order to do these sorts of things, the method is going to need access to a DbContext anyway.
Does this make sense, or am I missing something? I hate to write oodles of code and then figure out 3 months later that I went down the wrong road to start with. Where should these types of methods live? I know there is probably a purist answer to this, but I'm looking for a clean, real world solution.
First of all you are making a good decision to not abstract EF behind a repository.
With the EF Context you have a class supporting the Unit Of Work pattern which is handling your data access needs.No need to wrap it up in repository.
However this does not mean you should call the Context directly from your controller or viewmodel.
You could indeed just extend the DbContext however I suggest to use services to mediate between your controllers/view models and your dbcontext.
If e.g. in your controller you are handling a user request (e.g. the user has clicked a button) then your controller should call a service to archive what ever "Use Case" is behind the button.
In your case this could be a PermissionService, the PermissionService would be the storage for all operations concerning permission.
public class PermissionService
{
PermissionService(DbContext context)
{
}
public bool AddPermission(Employee e, PermissionType type) { }
public bool RemovePermission(Employee e, PermissionType type) {}
}
Your service ofcourse needs access to the DbContext.
It makes sense to use DI here and register the DbContext with a DI Container.
Thus the context will be injected into all your services. This is pretty straight forward and I do not see any extra complexity here.
However, if you don't want to do this you can simply new up up the Db Context inside your services. Of course this is harder / impossible to mock for testing.

How to solve this: application model and engine model mismatch when using JPA persistence?

The title may seems confusing, but it's not easy to describe the question in few words. Let me explain the situation:
We have a web application project, and a calculation engine project. The web application collect user input and use the engine to generate some result, and represent to user. Both user input, engine output and other data will be persisted to DB using JPA.
The engine input and output consist of objects in tree structure, example like:
Class InputA {
String attrA1;
List<InputB> inputBs;
}
Class InputB {
String attrB1;
List<InputC> inputCs;
}
Class InputC {
String attrC1;
}
The engine output is in similar style.
The web application project handle the data persistence using JPA. We need to persist the engine input and output, as well as some other data that related to the input and output. Such data can be seem as extra fields to certain class. For example:
We want to persist extra field, so it looks like:
Class InputBx extends InputB{
String attrBx1;
}
Class InputCx extends InputC{
String attrCx1;
}
In Java OO world, this works, we can store a list of InputBx in InputA, and store a list of InputCx in InputBx because of the inheritance.
But we meet trouble when using JPA to persist the extended objects.
First of all, it requires the engine project to make their class become JPA entities. The engine was working fine by itself, it accept correct input and generate correct output. It doesn't smell good to force their model to become JPA entities when another project try to persist the model.
Second, the JPA doesn't accept the inherited objects when using InputA as the entry. From JPA point of view, it only know that InputA contains a list of InputB, and not possible to persist/retrieve a list of InputBx in object of InputA.
When trying to solve this, we had come up 2 ideas, but neither one satisfied us:
idea 1:
Use composition instead inheritance, so we still persist the original InputA and it's tree structure include InputB and InputC:
Class InputBx{
String attrBx1;
InputB inputB;
}
Class InputCx{
String attrCx1;
InputC inputC;
}
So the original input object tree can be smoothly retrieved, and InputBx and InputCx objects needs to be retrieved using the InputB and InputC objects in the tree as references.
The good thing is that no matter what changes made to the structure of the original input class tree (such as change attribute name, add/remove attributes in the classes), the extended class InputBx and InputCx and their attributes automatically synchronized.
The drawback is that this structure increases the calls to the database, and the model is not easy to use in the application(both back end and front end). Whenever we want related information of InputB or InputC, we need to manually code to search the corresponding object of InputBx and InputCx.
idea 2:
Manually make mirror classes to form a similar structure of the original input classes. So we created:
Class InputAx {
String attrA1;
List<InputBx> inputBs;
}
Class InputBx {
String attrB1;
List<InputCx> inputCs;
String attrBx1;
}
Class InputCx {
String attrC1;
String attrCx1;
}
We could use this as model of the web application, and the JPA entities as well. Here's what we could get:
Now the engine project can be set free, it doesn't need to bind to how the other projects persist these input/output objects. The engine project is independant now.
The JPA persistence works just fluent, no extra calls to database is required
The back end and front end UI just use this model to get both original input objects and related information with no effort. When trying use engine to perform calculation, we can use a mapping mechanism to transfer between the original objects and extended objects.
The drawback is also obvious:
There is duplication in the class structure, which is not desired from the OO point of view.
When considering it as DTO to reduce the database calls, it can be claimed as anti-pattern when using DTO in local transfer.
The structure is not automatically synchronized with the original model. So if there are any changes made to the original model, we need to manually update this model as well. If some developers forget to do this, there will be some not-easy-to-find defects.
I'm looking for the following help:
Is there any existing good/best practices or patterns to solve similar situation we meet? Or any anti-patterns that we should try to avoid? References to web articles are welcome.
If possible, can you comment on the idea 1 and idea 2, from the aspect of OO design, Persistence practices, your experience, ect.
I will be grateful for your help.

MVVM - ViewModel/Model binding

I have some doubts about what are the best practices for MVVM using parent-child model relations.
In that specific case there are two models (data classes) called Group and Contact. The group is containing a list of contacts. Both of them are are implementing INotifyPropertyChanged interface.
In the view, there is a treeview displaying the hierarchy using DataTemplate and the associated ViewModel contains an ObservableCollections property.
I am wondering what is the best practice design in this case.... Having one property like above in the ViewModel which is bind to the xaml or createing a ViewModel for each model (like GroupViewModel and ContactViewModel) and instead of ObservableCollections having an List.
What is the best way (design wise)? Shoudl I bind the Model or the ViewModel to the xaml?
I'm afraid, you mixed some things up. The basics of MVVM are
Model - Contains the data the application is working with. It should be kept as simple as possible.
ViewModel - Reflects the state of the application and contains the business logic. It's the business layer.
View - Interprets the ViewModel to provide a visual representation of the business layer and its state.
With this three parts, it's pretty easy to provide separation of concerns and a decoupled architecture. If you want to read more, click here.
Back to your questions:
In that specific case there are two models (data classes) called Group and Contact. The group is containing a list of contacts. Both of them are are implementing INotifyPropertyChanged interface.
That's a bit odd. Usually, you don't need to implement INotifyPropertyChanged in the model classes, since the VM should handle value changes from the view.
But it's imaginable to have that mechanism in the model layer too. But since you don't want to track changes on this layer and IMHO the VM should take care about, you don't need it.
[...] Having one property like above in the ViewModel which is bind to the xaml or createing a ViewModel for each model (like GroupViewModel and ContactViewModel) [...]
Yes, this is usually the approach. For each model class, which should be passed to the view layer, you would create a ViewModel.
[...] and instead of ObservableCollections having an List.
That's definitely a No. If you use a List<T>, the view would not be aware of the changes (add, remove) to collection.
What is the best way (design wise)? Shoudl I bind the Model or the ViewModel to the xaml?
Simply stick to MVVM. The view is aware of the VM, but the VM is not aware of the view. Additionally the VM is aware of the model, but the model isn't aware of it. That implies, that you should always bind the VM to the View.
Edit
The following is totally legit.
public class Address : ViewModelBase // implements INotifiedPropertyChanged a.s.o.
{
public string Street { /* you know what comes here */ }
public string ZipCode { /* ... */ }
public string City { /* ... */ }
/* more properties */
}
public class Person : ViewModelBase
{
public string Name { /* ... */ }
public Address Address { /* ... */ }
}

Questions on changing from WinForms to WPF

I have recently been looking for a way to bind data in WinForms using MVVM.
I ended up creating a custom implementation of the MVVM pattern.
However, due to the lack of two-way binding, I have decided to give WPF a try.
I already have the Model, which encapsulates the non-ui functionality. For example the Model reads a configuration file, has a few properties, listens for incoming data on a socket, and saves incoming packets if needed.
Some of the Model's properties throws an exception if they are set out of range. I.e. the validation is done in the Model.
How is validation usually done in WPF? I have read a good deal of articles, and there seems to be some consistency in putting validation in the ViewModel. In fact, most articles only use ViewModel and View. Has the Model been buried?
Glad to see your decision to move away from custom implementations of MVVM when so much already exists that just ... works.
WPF is very strong for two way binding and that gives it its' greatest strengths.
The view model is bound to the view and acts as the mechanism to communicate with the data layer. Also Entity Framework (if you are on framework 4.0) will give you a great data layer for populating your entities in your ViewModel. This basically becomes your Model. It gives you an encapsulated form of UnitOfWork as well as Repository patterns.
While your view model in all examples are usually on a one-to-one basis, if the design calls for it you can have view models that span multiple views. I have a "menu" which displays key identifiers from each item in the list and a detail form that shows all fields for editing from the same object. So I span the view between the two.
You can hard code the view model in the xaml binding it to the datacontext or you can use Unity and inject the viewmodel into the view. Unfortunately the injection requires adding one public property for the purpose of setting the datacontext. So you'd have code like this:
public class MyView:Window
{
public MyView(MyViewModel model)
{
InitializeComponent();
ViewModel = model;
}
public MyViewModel ViewModel
{
set{ this.DataContext = value; }
}
}
So the rest is just TwoWay binding for each field and the setter can encapsulate single value editing. Your error message can even be bound to a text field on the form and it displays when the value is not null.
Also if you dig into Unity you will also get a truly great function called Event Aggregation which basically provides a vehicle for publish/subscribe of events and that ties into your ICommand implementation when getting a button click handled.

Question on Structure

I have an ASP.NET MVC 2 project. I've decoupled layers. I have a service layer and a repository layer.
The controller calls service methods and only the service layer calls methods in the repository.
The problem is:
A method in my repository class uses LINQ joins. From this method, I would like to return a type with merging some data from joined tables. (i.e, Name = a.Name, Position = b.Position) And I always return IEnumerables in my repository class. So in this case, it seems I need to define a new type for (Name, Position), and return that type from the repository function. But, then, I'll have to remap that class to some other ViewModel class. (Because I'm seperating concerns, I shouldnt use viewmodel classes in repository right?) This leads to many different classes. EF classes, classes for joined tables, and viewmodel classes.
Am I in the right path?
Please enlighten me.
Thank you
Consider defining those classes at the repository layer. Essentially they're DTO classes, and it sounds like you were on the track I'd have taken.
Any reason why you were expecting to remap that class to some other ViewModel class?
public class EmpPosition()
{
public property Name{get;set;}
public property Position{get;set;}
}
//Repo
public IEnumerable<EmpPosition> GetEmployeePositions()
{}