ASP.NET MVC 2 Data Validation: Does this carry from a DomainModel to a ViewModel? - asp.net-mvc-2

Given my understanding of MVC and DDD (critique as necessary):
Domain Models can be created by Factories, and persisted by Repositories. These are POCO objects.
View Models contain partial or complete Domain Models as needed by the view. They are generated by a service that interacts with a repository. Thus Domain Models never make it to the view directly. Likewise, ViewModels are never persisted.
You will very likely have multiple View Models for the same Domain Model because you could show it on multiple views.
That said, adding data validation to the Domain Model removes any kind of redundancy.
So how do you get the ViewModels to inherit the Domain Model data validation?
I wouldn't expect simply referencing a Domain Model from a View Model to work.

I asked this same question at the patterns & practices summit last October while speaking to Brad Wilson and he did not have a global solution.
One idea I discussed with him was extending an object mapping library such as AutoMapper to also map validation from the domain model to the view model.
In designing a framework to facilitate this scenario, some things to consider:
Validation rules may depend on the context and thus may be unique to the particular view model. The Enterprise Library Validation Block allows the setup of validation logic using a configuration file - this for example, could be extended to transfer to view models as well.
The View Model could have properties which are not part of the domain model, such as a property that specified that a certain "agree to terms" checkbox has been checked. This property requires validation however it is specific to the view and use case, not the domain model. This scenario serves as another argument to keep the validation logic separate, at least partially.
For the purposes of maintenance and clarity it may be easier to duplicate certain validation logic for the domain model and view model instead of using a mapping framework.

Related

Non business logic database access in DDD

just starting with DDD. I understand that all the domain entities and their logic should be kept in Domain layer along with repository interfaces. In my application I store some data in the database that is used to construct parts of the user interface (presentation layer) at run time. Where should I keep the poco classes and repository interfaces for such types, in Application layer or Domain layer. I can not make out because these objects will not have any domain related business logic but they need to be hydrated from the database and I am using EF so for data access I will need entities and repositories so to me obvious choice is to keep them with all other entities and repository interfaces in domain layer but that breaks DDD rules
I think you've answered your own question:
In my application I store some data in the database that is used to
construct parts of the user interface (presentation layer) at run
time.
Access to data that is used to serve the UI should be encapsulated in the presentation layer. This is different from the application layer in that a DDD application layer implements use cases by orchestrating repositories and delegating to appropriate entities, domain services - it forms an API around your domain layer. Different presentation implementations can use the same application service.
However, different presentation layer implementations may require different data. Therefore, place presentation data access directly in the presentation layer. This can be implemented with EF which is not exclusive for DDD scenarios.
A good way to think of it is this - if you had to replace EF with stored procedures for performance reasons, you should not have to modify your domain code. So anything that blocks that needs to be hidden behind an interface and made replaceable.
Repositories CAN be a part of domain logic. However what should not be is the mechanism for persistence. This can easily be encapsulated into a DAL service or other object, which of course is programmed to an IDALService interface. So when you need to switch persistance (for example, moving from EF to a NoSQL solution) you simply write an alternative version that implements the IDALService interface, and you're good to go. The repositories can still do the logic within them, but are now using a new way to store them (this is an Inversion of Control idea).
As for the POCO objects, in DDD the real question is what do they represent? Are they entities, that need to be persisted? Are they value objects? Don't let the technology (EF) determine what the structure of your object model is, instead provide means to translate to an application scope.
In the Application layer. Keep the domain intact and isolated.

Entity Framework, MVVM, and Calculations Classes

I'm working on a database application that manages industry-specific inputs and then runs that information through somewhat complicated calculations, lookups, etc. to return a series of other values and a go/no-go conclusion.
I've decided to use Entity Framework (code first for provider independence) and WPF (MVVM pattern). I'm using the POCO entities as my data model and the view model is handling the usuals like basic data / business rule validation.
It seems EF + WPF/MVVM are great at displaying and validating input and getting it into the database for querying for your typical business application like a products, customers, orders setup. But it's not at all clear where to plug in a "calculations layer". Between the view models and the data models (my POCOs), things are already feeling a bit bloated, and now I'm facing adding another layer very much like the other two.
Perhaps the best way to approach this is to make the calculations layer a sort of meta-view model and push as much of the validations, change notification, etc. into them and run with lighter actual view models.
Anyone run into a situation like this?
Edit
Turns out what I really needed was to thin the view models and beef up the entities. So I lightened the view models, moved property change notification and basic validation to entities to allow for direct binding, and made calculation classes directly consume entities as well as adding some basic routines to entities. Thanks for the links on thought ADM articles #Peter Porfy.
For moving validation closer to entities, used Fluent Validation (excellent suggestion #Gloopy!). To make it easier to implement property changed notification on entities, adapted this technique. And to avoid having to create endless property wrappers in view model (to set HasChanges property) I used Josh Smith's PropertyObserver.
MVVM stands for Model-View-ViewModel, where the Model layer contains everything what models your actual domain problem.
So it depends on what you mean 'calculation layer'.
Put it where it belongs.
If the actual operation belongs to a domain entity, then you should put that logic into the entity. Don't make anemic domain models:
Article from Martin Fowler about ADM.
DDD works perfectly with EF code-first.
If something doesn't belong to any entity then probably you should expose that as a service. Then use that from your viewmodels through an interface.
A dependency injection container could make your life easier here, but you can live without it.
You aren't plugging another layer because it's the model layer. Your viewmodels should stay as thin as possible, just modelling your view's state and forwarding actual business operations to the entity/service classes.
I'd probably create an interface/object to handle calculations (or several if they can be split up logically) and pass that object in wherever you would want to use it. You might benefit from using a dependency injection framework maybe this post can help with that so you wouldn't have to explicitly instantiate your objects where you need them.
Also this post mentions FluentValidation.NET which may not apply completely but there are likely some good patterns to learn from/use there as well.

Entity framework and Business Layer / logic

im doing some self-study on architecture of a MVVM-light - EF Application
im trying to build a product/Receipt like app.
I have a Db/EF with a Product and Receipt Table/Entity in a many to many relation.
then i have a DAL wich simply uses Linq to do simple CRUD.
the question is where and how to put my business logic in this app.
a couple of ideas came to mind
option 1
-make a ReceiptBo (Receipt business object)
wich inherit the Entity Receipt class and Icollection(ProductBo)
the ReceiptBo class would be responsible for adding Product,calculating total and subtotal and calling the Dal for inserting.
maby this option seemed a little overkill.
option 2
-put the calculating methods in the generated Entity objects by using partial classes
and simply using the BuisnessLayer to call the Dal.
this would make the Buisnesslayer Classes obsolete in my opinion and im not sure that Entity classes should be used for Business logic at all ?
option 3
-make the Business Classes but dont bother using inheritance, just add products to the Entity's and do the calculations there and call the Dal for insert.
wich seems simple but not very elegant.
option 4
-none of the above and im clueless
right now im not using WCF but the idea is that i want to make this app loosly coupled so that it would be easy to implement it and further extend it.
also im a little confused about what an Business layer is. in some examples it is more used like a Dal that also does the computing, then others say this is not done.
some help would be great. thx
ps: sorry for my bad english
Really, I would go simple here and choose a common multi-tier architecture designed as follows:
a data access layer (basically, your Entity Framework model along with all your entities)
a business layer that exposes methods to access to your entities (CRUD methods + any custom method that run some logic)
a service layer that exposes stateless methods through WCF (service+data contract)
the presentation layer (in your case using MVVM pattern)
Views (XAML pages)
ViewModels (C# classes)
Model is represented here by the entities that are exposed through WCF by the service layer
I wouldn't add any method directly in the entities. All methods are defined in the business layer, and exposed by the service layer.
Usually I keep my business logic in my ViewModels, not my Models, and I view EF objects as Models. At most, they'll have some basic data validation, such as verifying length or required fields.
For example, an EditRecieptViewModel would validate business rules such as verifying values are in a specific range, or verifying that users have access to edit the object, or performing some custom calculations when a value changes.
Also, don't forget that ViewModels should reflect the View, not a Model, so not every Model will have a ViewModel of its own

MVC3 App/Service Layer/Repository Layer/POCO Classes/EF4 - Questions!

I am new to this whole design concept, and in reading for the last few weeks I have gathered a lot of information, but it seems scattered and conflicted. Terms are mixed, and I am just having a hard time wrapping my mind around this.
The pattern I am using is like this and assume the flow as follows:
MVC Application
The controller(s) process the request/response from the client for a given view. Inside the controllers action methods, they contact the services (Service Layer) and either request objects to build the view models, and sen the objects from the view models back.
View Models
I am using strongly typed view models to and from the views.
Are view models DTO's? Should they contain just simple properties like Name, AddressLine1, Address City, etc, or should they contain complex properties, multiple objects, etc.
Is the validation in the view model. If so would it be validation like required fields, field length, etc. Then validation like user name already exists, or where you would need to interact with other objects in the service layer?
Can the view models just contain the POCO classes returned from EF, or should I be using the AutoMapper?
If using AutoMapper and DTO, are DTO's clones of the POCO classes?
Would you map in the controller, view model, or in the service layer below?
Services
To me, the service(s) are objects that contact the repository(s) to get POCO objects back from the EF. This is where all of my business logic is. Once the service hands an object back to a repository to be persisted to the EF, they are considered valid objects. Is this correct?
Repositories
There is no business logic in them, they are just used to transport objects between the service(s) and the EF. Is this correct? I am implementing Interfaces here with generic repository. Then you could extend the generic repository for special needs?
Questions About Terminology
1) Is a business object equal to a domain object? How much logic should a domain object contain?
2) Is the domain model the EF model? I am using the Model-First approach.
3) Dependency Injection - Should I be using this? I understand how it works, just don't get the real benefit. I was playing with Ninject.
I think the community would benefit from some sort of wiki that contained all the best practices with code samples. Is there something like that out there? A lot of the samples out there are very simple, and a lot of the Microsoft samples do not use this pattern even when claiming to.
Thanks in advance to everyone who has and will help me with this.
BTW - I think StackOverflow needs a little, "Buy Me A Beer" button next to the "Accept Answer" checkbox :)
Are view models DTO's?
Could be considered a sort of data transfer objects between the controller and the view.
Should they contain just simple properties like Name, AddressLine1, Address City, etc, or should they contain complex properties, multiple objects, etc.
Ideally simple properties but could also aggregate other view models but no models there (ex: like EF models).
Is the validation in the view model.
There are two type of validation logic: business validation (ex. username already exists) which goes into the service layer and UI validation (ex: username is required) which goes into the view model.
Can the view models just contain the POCO classes returned from EF, or should I be using the AutoMapper?
No EF in view models. View models are POCO classes with simple properties and other complex properties pointing to other view models. They could also contain methods in order to properly format the data that will be presented on the particular view those models were intended for.
If using AutoMapper and DTO, are DTO's clones of the POCO classes?
Not sure I understand this question.
Would you map in the controller, view model, or in the service layer below?
The controller.
To me, the service(s) are objects that contact the repository(s) to get POCO objects back from the EF. This is where all of my business logic is. Once the service hands an object back to a repository to be persisted to the EF, they are considered valid objects. Is this correct?
Yes.
Is the domain model the EF model?
If you are using EF Code first approach then yes, otherwise no (if EF pollutes the domain with EF specific attributes and classes).
There is no business logic in them, they are just used to transport objects between the service(s) and the EF. Is this correct?
Yes.
I am implementing Interfaces here with generic repository. Then you could extend the generic repository for special needs?
Yes, but don't get too fancy. Normally Repositories are for CRUD operations. It's services that should contain the business logic.
Is a business object equal to a domain object?
Yes.
How much logic should a domain object contain?
This will depend on the amount of domain logic you have for the particular project you are working and on any existing domain logic you could reuse from older projects you or someone else have worked on.
Dependency Injection - Should I be using this?
Yes, absolutely.
I understand how it works, just don't get the real benefit
It provides weaker coupling between the different layers of your application which in turns makes them easier to unit test and reuse in other projects.
I think the community would benefit from some sort of wiki that contained all the best practices with code samples.
I agree.
Is there something like that out there?
I doubt it.
BTW - I think StackOverflow needs a little, "Buy Me A Beer" button next to the "Accept Answer" checkbox
Can't agree more.

Confusion over MVC and entity model

My confusion stems from the fact I am using 2 different walkthroughs on building mvc applications, namely: Steven Sanderson's pro asp.net mvc and the online mvc music store. The former creates a domain model, placing the entity model in there along with repositories, while the music store demo places the entity model in the mvc model folder. Which of these is the best approach. Should the entity model and associated repositories exist in a separate domain layer, or in the MVCs model folder.
Separation of concerns
Model folder in Asp.net MVC project template is indeed very confusing. Most developers not knowing enough about MVC pattern think that application/domain model = data model. Most of the time, that's not the case.
Take for instance a user entity that may be in several different forms:
NewUser is an application model entity that has most properties of a user, plus two password properties that can be declaratively validated
User data model entity has all usual user properties and one password property
User application model entity has all the usual properties and none for password
So you can see by this simple example there are multiple models that differ between each other. And when you have a multi-assemblied application, putting application model in a separate assembly is very wise, since all assemblies will most probably communicate using these objects only. No data model entities should be transferred outside data assembly/tier to make use of SoC...
So in the end it's ok to put data model in the Model folder when building a small scale simple application, but in all other cases it's probably better to use a separate application model assembly that's shared between all assemblies. And have a separate data model that's only used in data tier assembly.
Read this answer that may help you see things a bit clearer.
And this one as well.
I would recommend against using the Model folder and use a separate assembly instead. You'll have better separation and improved scalability.
Strategically it makes sense to place the EF Model in the same folder as the repositories, because it just is a part of the Data-Access-Layer inside an application.
Logically it would be better to place the EF model in the Model directory as it creates all classes needed to reflect the database in an application. (And if you open the Class View it looks way better to have all those classes residing in a folder called Model instead of Repositories)
At our company we've had the same problem and decided to go with saving the EF model in the Model folder.
After all it's up to you what you do. The most important thing to do here would be to document all kinds decisions that happen during development (when, why and based on what).
Documenting everything could prevent later WTF's