Is this class structure method correct/desireblable? (MVC/C#)
I'm building a MVC application which is a bit more complex than what I usually do and I want to try a new class structure. Basically theres a lot of reading going on. Just 5-10% of opera开发者_StackOverflow中文版tions will be insert/update against the database.
Because of this, I'm thinking of creating base DTO classes which would be returned from a database layer. Then, business objects would inherit from the DTO class in order to extend the basic structure with all the validation and business rules.
Example:
namespace Project.DTO
{
public class Employee
{
public string Name;
public string Surname;
...
}
}
namespace Project
{
public class Employee : Project.DTO.Employee
{
public bool IsValid()
{
...
}
}
}
Is this a good approach? What I haven't thought off yet is how to use them inside the MVC, as the "correct" way would be to implement model classes. I believe I could create model classes that inherited from the DTO objects as well... but I'm unsure.
I would also need a way to handle all validation functions with some kind of Interface, as to avoid repeating to much generic code on the GUI.
Thanks in advance!
I would probably use a completely different approach. My primary thoughts are these:
- I would like looser coupling between the classes, so I would not have my model classes inherit from my DTO objects
- I would probably not include validation logic in my model classes
This would lead to the following structure to start with:
namespace Project.DTO
{
public class Employee
{
public string Name;
public string Surname;
...
}
}
namespace Project
{
public class Employee
{
public string Name { get; set; }
public string Surname { get; set; }
}
}
When it comes to the validation logic, I would make an interface for the validation logic, that is injected into the Emplyee
class:
public interface IValidator<T>
{
bool IsValid(T objectToInspect);
}
public class Employee
{
private readonly IValidator<Employee> validator;
public Employee(IValidator<Employee> validator)
{
this.validator = validator;
}
public string Name { get; set; }
public string Surname { get; set; }
public bool IsValid()
{
return validator.IsValid(this);
}
}
This opens up your design for a whole range of features, including using IoC containers and better support for testing.
What if validation has to check with a rule whose parameters must come from database? Your entity would not have a knowledge and the way to access that parameter.
Creating Model/ViewModel is good but validation usually require more complex logic which would warrant dedicated classes - so I would not normally implement IsValid
on my entity.
However, you can use System.Component.DataAnnotation
validation attributes against simple properties of your entities.
精彩评论