I've been developing a web app using asp.net mvc and nhibernate. I'm trying to follow some principles of DDD and best pratices of Asp.Net MVC. My question is about Clean up POST with VIewModels. To illustrate my question, look this entity on my domain model:
[Validator(typeof(EntityValidator))]
public class MyEntity {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Email { get; set; }
public virtual decimal UnitPrice { get; set; }
public virtual Category Category { get; set; }
public MyEntity() { }
}
It's mapped with nhibernate and works fine. For validation, I'm using Fluent Validation, and I have this class:
public class EntityValidator : AbstractValidator<MyEntity>
{
protected IEntityRepository EntityRepository { get; set; }
public EntityValidator(IEntityRepository entityRepository) { // injected by a IoC Container
this.EntityRepository = entityRepository;
RuleFor(x => x.Name).NotEmpty();
RuleFor(x => x.UnitPrice).GreaterThan(0);
RuleFor(x => x.Category).NotNull();
RuleFor(x => x.Email).NotEmpty().EmailAddress().Must((entity, email) => EntityRepository.ExisteEmail(entity.Email));
}
}
I preffer to use Fluent Validation than Data Annotations because it's more flexible and works fine with Asp.Net MVC. It's configured and works fine too. So, I have this ViewModel:
public class EntityViewModel {
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public decimal UnitPrice { get; set; }
public int IdCategory { get; set; }
}
Now, I'm trying to do a ViewModel to make a clean up POST of my entity in some actions (like INSERT, UPDATE) because I'm using nhibernate. I
don't know if it's right to create a validation for viewmodel, because I have my own on my entity, so, how can I do this? How have you been doing
to POST your entity on actions to persist it? How you validate it and post erros on ModelState of MVC?
I'd like to see some code of how to do it, if it's possible.
Thanks everyone!