Is it okay to use attributes and IValidatableObject on domain objects? - asp.net-mvc

I am used to working with entity objects and now I am switching to DDD principles so I will start using domain objects.
I am used to decorate the properties of my entity objects with attributes such as RequiredAttribute or StringLengthAttribute. I am also used to implement the IValidatableObject on my entity objects.
My question is - is it acceptable to use attributes and IValidatableObject on my domain objects? Is it consistent with DDD? Thank you.

Your domain model should work only with business concepts, it shouldn't have any direct relations to DAL or View. Attributes you have applied means that you use your domain model as view model. Create separate viewmodel. Don't use your entity objects which describing your storage model as root class for your domain.Create new classes for your domain objects. Add methods which clear explain business -
ChangeLastName(string newName) instead of obj.LastName = "Some name"
CreateNewPost(string text,string author) instead of obj.Posts.Add(..)
You can write some extension methods to make mappings, like ToViewModel, or do it some else.One interesting design/infrastructure pattern is CQRS & EventSourcing. It allows you avoid mappings, but have some drawbacks (like transactions between aggregates). And last - in most cases simple CRUD operations more suited - fast, simple, easy.

From a DDD point of view, the domain model is best kept lean with the use of exceptions in your entity’s behavior methods, or by implementing the Specification and Notification patterns to enforce validation rules.
It can make sense to use data annotations at the application layer in ViewModel classes (instead of domain entities) that will accept input, to allow for model validation within the UI layer. However, this should not be done at the exclusion of validation within the domain model.

Related

Should business logic ever be in the model? (MVC4)

I have a class called "Stores" in my MVC app that has a class called "IsInCompliance" which depends on the values of several other fields. The logic would go through and say "if this, this, and this is true, then IsInCompliance is true".
Should this belong in the model definition, or would this logic be better placed in a service layer or controller? I figure I have four options:
Logic contained in a method within the model
Logic contained in a controller that writes back to the model
Logic contained in a Service that the model calls
Logic contained in a Service that the controller calls
Which is best? If 3 is the best, isn't there a circular dependency there (since my model project depends on the services project, which depends on the model project)?
Number 4 is the correct approach.
Controllers should act as a thin "traffic control" layer and delegate all logic to a service layer beneath them (or if it's not too obvious logic, to a business layer - but that's a different architectural question).
Your model should generally be a pure POCO structure, with optionally micro-logic of things that are internal to the data model. For example, ID generation and data integrity operations.
Most of your logic (for relatively simple / CRUD-based apps) should generally reside in the Service Layer.
This is a matter of preference/style, but I have always believed that methods that are germane to the Model object belong in that object.
Take this as an example (I'm coding on the fly without an open VS.NET instance, so please forgive any syntax errors, just trying to use this as a vehicle for communication):
public class Person
{
public Int32 Age { get; set; }
public bool IsEligibleToEnterLegallyBindingContract()
{
return Age >= 18;
}
}
I would assert that a model object that contains methods that introspects its own properties and is not dependent on messages and/or properties of other model objects is good object design and a good modeling approach in an MVC environment.
Update I had a discussion with a colleague regarding this, and he pointed me toward the Anemic Domain Model, an excellent article by Martin Fowler. I read this article several times after my colleague recommended it.
The closing paragraph from Mr. Fowler's article (this is a direct quote from martinfowler.com and credit is acknowledged and given to that site):
"In general, the more behavior you find in the services, the more likely you are to be robbing yourself of the benefits of a domain model. If all your logic is in services, you've robbed yourself blind."
MVC is all about separating concerns. Keep it that way. Separate your logic from your data by placing your business logic in a separate class (layer).
Usually I perform actions on the Model rather than IN the Model, however it is sort of a personal preference.
I would (in your case) write the logic in the Service layer, then do a coordination call from the Controller that would work on the Model.
That said however, I believe some people refer to this as an Anemic Domain Model.
I don't think any of the approaches are wrong, but I personally would go for Number 4.
I guess it depends on your coding style.
Either option 1, or option 4 is correct depending on who you ask.
For something like this, i think option 1 is correct.
If IsInCompliance only depends on the value other properties in the model then it should be in the model.
If the value of IsInCompliance depends on other classes then yes it should be in a service layer.
Moving stuff like this to a service layer results in an Anemic Domain model where your model classes end up just being dto's
In object oriented design, this is considered an anti pattern.
There is still plenty of stuff that needs to be in a service layer, i just don't think this is one of them.

Use data annonations in ASP.NET MVC using DDD

I've started to develop ASP.NET MVC application using Entity Framework and I wish to use DDD. It's my first time using DDD in ASP.NET (used until now in PHP), so I'm little confused.
I'm using code-first approach, so I'm creating my entites in the core and then the DbContext in the Infrastructure.
My questions is about data annotations: Is it OK to annonate the entities in the core? with Required, DataType, etc. or I have to create entries with pure C# validation (in the setters and getters) and then create a map objects for the database creation?
For example, I got:
public class Account
{
public string AccountName { get; set; }
}
Can I annonate the AccountName with [Required] or I need to create a map class which will just reflect the exact same properties in the Account class but will have attributes and that will be the class that I'll use in Entity Framework DbContext?
Thanks!
Neither.
Your entities should have barely any public getters or setters. Domain model is a behavioral model, not a data model. Your entities should have private fields and methods that changes the entity state. Those methods should have a business meaning and should protect entities invariants (validate input). For example - we have UserAddress and want to change it. Is it just user.Address = newAddress? NO. What's the meaning of changing that? Maybe your User want to FixMistypedAddress(str). Or maybe your UserMoved(newLocation)? Different business rules may apply tho those scenarios. For example when UserMoved() we want to send him a champagne bottle, but not when he just fixed a typo. You should already see that there is no use of data annotations here because we don't just set properties but we do meaningful operations.
Entities should always be valid. That mean there should be no way to put it in an invalid state. Data annotations only allow you to check whether the object is valid or not. They not guarantee is will be valid all the time.
IMO Data annotations are fine for:
Using Entity Framework in a CRUD application (no DDD applied)
In DTO or ViewModels. In other words - for validating user forms, not entities.
So the first quiestion for you is: Are you doing CRUD or DDD?
I'd say either way is fine.
If you want a more pure approach you would create a buddy class that has the metadata on it however it is also acceptable to put it directly on the domain class.
In the end it comes down to how much you want to remain "pure" and how much extra work you want to put into maintaining buddy classes, not to say that it is a bad thing.

How to create model quickly&elegantly with Linq To Sql in asp.net mvc?

Ok straight to the issue. I can get object mapping to tables easily with Linq To Sql. For instance: class Product, class Order, class Order_Detail from Northwind. IMO, these 3 object have already met model's meet. But i can't put some useful attr([Required] [HttpPost]) on properties of them(except modifying design.cs, which is not recommended).Do i have to create ProductModels OrderModels with the same properties myself, and maybe some additional DAL-like classes to turn the linq2sql objects to models??
EDIT:
Even if i put design.cs and my models in the same namespace, how can i make two partial classes have the same properties??
Yes, you should create DTO's for each Linq to SQL model, it is not considered a good practice to pass Linq2Sql objects through your layers.
Optionally, look into to using Entity Framework Code First. It is stupid simple to use and you can add validation attributes directly to your POCOs, which are enforced on the data persistence side as well as the presentation side in MVC.
here's a good EF codefirst primer : http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx

entity framework POCO + recommended patterns

We do like EntityFramework (CTP5) quite a lot and Using it along with ASP.NET MVC3.
What I dislike is;
things are mixed in together.
I can place a DisplayAttribute, RequiredAttribute, RangeAttribute, CompareAttribute together in the same class which means I am mixin in database validation, some business logic and UI alltogether. I can even place ScriptIgnore attribute to customize it as a Json DTO object. So I can use the same POCO class for Persistance, Presentation, DTO and Business Object, and as my domian model.
Which design patterns do you follow along with EF POCO + MVC3 toolset. What layers do you have?
What resposibilities do you add to your classes (Is Your POCO class also your Domain Model)
I use View Models to solve this problem. Validation and UI presentation attributes go to the view model. In this pattern the controller uses a repository to fetch an EF model, maps this EF model to a view model (I use AutoMapper for this) and passes the view model to the view. Because the view model contains all the UI presentation attributes the view behaves as expected. Each view must have its own view model. This means that you could have multiple view models associated to the same EF model but contain a different subset of properties and display formatting attributes based on the specific requirements of the view.
The process works the other way around as well: the controller receives a view model from the view as argument. It maps the view model back to a model and passes the EF model to the repository. UI validation attributes are handled on the view model because you could have different validation requirements in different views: think for example Insert/Update views. In the insert view you will be creating a new entity thus the Id property won't be required. You won't even have an Id property on your view model in this case. In the update view on the contrary the Id property will be required.
My POCO classes are almost always domain models and almost never view models so I don't have these problems.
The best practice is to use special "view model" class when passing data from controller to view (or as JsonResult). In such case you mark UI based attributes in that view model. In most cases (except pure crud applications) you need to display something more or something less then your domain object so you still need some view model (unless you use ViewData directly).
Data annotations on domain object makes sense only if you want to use them for business/data level validation which can take different rules then UI validation.
If you want to follow strict DDD where POCO classes are domain objects = offers methods performing domain logic on instance of object you should go even further because in such case your business facede should not expose domain objects to controller. In such case you will end up with data transfer objects exposed on business facade and consumed in controller. I'm not purist so in this scenario I'm open minded to using data annotations on DTOs directly but it depends on another requirements.

DTO = ViewModel?

I'm using NHibernate to persist my domain objects.
To keep things simple I'm using an ASP.NET MVC project as both my presentation layer, and my service layer.
I want to return my domain objects in XML from my controller classes. After reading some posts here on Stack Overflow I gather DTOs are the way to go. However, I've also come across posts talking about the ViewModel.
My question: Are Data Transfer Objects and ViewModels the same thing? Or is a ViewModel a kind of sub pattern of a DTO?
The canonical definition of a DTO is the data shape of an object without any behavior.
ViewModels are the model of the view. ViewModels typically are full or partial data from one or more objects (or DTOs) plus any additional members specific to the view's behavior (methods that can be executed by the view, properties to indicate how toggle view elements etc...). You can look at the viewmodel as all the data for a view plus behaviors. ViewModels may or may not map one to one to business objects or DTOs.
By the way, NHibernate projections come in handy if a certain viewmodel needs a subset of the data from a persisted object.
ViewModel in ASP.NET MVC practice is the same as the DTO, however ViewModel in MVVM pattern is different from DTO because ViewModel in MVVM has behaviors but DTO does not have.
DTO != ViewModel
In the MVVM pattern the ViewModel is used to isolate the Model from the View. To represent the Model you could use simple DTO classes, which again is mapped to a database through e.g. NHibernate. But I've never seen a ViewModel class which is modelled as a DTO.. ViewModel classes mostly have behavior, which DTOs don't have.
DTO - Data Transfer Objects are exactly as it says, containers for transferring data. They have no behaviour but merely a bunch of setters and getters. Some people make them immutable and just create new ones when needed rather than updating existing ones. They should be serializable to allow transfer across the wire.
Generally DTOs are used to ship data from one layer to another layer across process boundries as calls to a remote service can be expensive so all the required data is pushed into a DTO and transferred to the client in one chunk (coarse grained).
However, some people use the notion of screen bound DTOs (nothing to do with crossing process boundries). Again these are populated with the required data (generally the data required for a particular screen and could be an aggregation of data from various sources) and sent to the client.
http://blog.jpboodhoo.com/CommentView,guid,21fe23e7-e42c-48d8-8871-86e65bcc9a50.aspx
In simple cases as has already been stated this DTO can be used for binding to the view but in more complex cases it would require the creation of a ViewModel and unloading of data from DTO to ViewModel which is obviously more work (when applying MVVM pattern).
So again as already stated DTO!=ViewModel
and
DTO and ViewModel have different purposes in life
For some simple views I'll use my DTO as my models, but as Views become more complex I'll create ViewModels.
For me it is a balance between quickness (using DTO, since I already have 'em) and flexibility (creating ViewModels means more separation of concerns).
First, the major difference is that ViewModel can have behaviour or methods that DTO Must Not !!!
Second, Using DTO as a ViewModel in ASP.NET MVC make your application tightly coupled to DTO and that's exactly the opposite purpose of using DTO. If you do so, what's the difference using your domain Model or DTO, more complexity to get an anti-pattern ?
Also ViewModel in ASP.NET can use DataAnnotations for validation.
The same DTO can have different ViewModels Mapping, and One ViewModel can be composed from differents DTO (always with object mapping not composition) . because i think it is even worse if you have a ViewModel that contains a DTO, we will have the same problem.
From your presentation layer, think about DTO as a contract, you will receive an object that you have to consider as stranger to your application and don't have any control on it (even if you have ex the service, the dto and presentation layers are yours).
Finally if you do this clean separation, developpers can work together with ease.
The person who design ViewModels, Views and Controllers don't have to worry about the service layer or the DTO implementation because he will make the mapping when the others developpers finish their implementation...
He can even use Mocking tool or manual mocking to fill the presentation layer with data for test.
If you need to change or enhance the DTO then create a ViewModel. It's also OK for the ViewModel to reference the DTO as a complex property.
In practice, you will generally want to add view-specific properties or methods to the model you are using in the view. In such cases,
never modify the DTO for your view requirements. Instead, create a ViewModel and map from your DTO to the ViewModel.
If you will use DTO as ViewModel, that means you are making high dependency on DTO because of some reason you are changing DTO then it could impact on ViewModel.
Better use DTO & convert into viewmodel.
We can use DTO same as Model class and we can use viewmodel when we needs to show/use multiple models data/property in a single view. Example: I create some model using entity framework database first. So, now all the model generate based on the database. and now we need data annotation, for those data annotation we can create a folder name DTO, In this DTO folder, we can keep all the models exact which already generate and add data annotation above the property. Then we can use any operation(use controller , views) using this DTO classes. And when we need complex view, I mean when we need multiple classes data in one view there we can use viewmodel. For viewmodel we can create a folder name viewmodel, then create a custom class and keep that property which we need. I tried to clear myself. Any suggestion highly appreciated.

Resources