I have got an MVC application in which the Domain Model (Data Model + Business Model) resides in a different class library. I am using an interface exposing some methods which must return data but not necessarily the entire representation of my domain objects.
My question is How should I return the data?
Should I create a kind of view models on the Business Model layer and then match them with my real view models on the main application (views-controllers-viewmodels
)?
Should I return this data as dynamic objects?
Should I return the entire domain object event I need a couple of properties only?
What is the best approach to follow?
This is an example to give a better idea about the situation:
//Domain Class
public class User
{
public string UserName { get; set; }
public int UserId { get; set; }
public string UserPassword{ get; set; }
public string FirstName{ get; set; }
public virtual ICollection<ApplicationUserTeam> ApplicationUserTeams
{
get { return _applicationUserTeams; }
set { _applicationUserTeams = value; }
}
}
public interface ITrackAttendance
{
dynamic GetUsersCompany(int CompanyId);
}
public class TrackAttendanceServices : ITrackAttendance
{
//Method returning a Dynamic Object???
public dynamic GetUsersCompany(int CompanyId)
{
using (var _ctx = new TrackAttendanceDb())
{
return _ctx.Users.Where(u => u.ApplicationUserTeams.FirstOrDefault().Team.CompanyId== CompanyId)
.Select(u =>
new
{
UserName = u.UserName,
UserId = u.Id,
userState = false
}).ToList();
}
}
}
Project Architecture:
My Solution:
Thanks to all the experts who have given their opinion for this question, I have decided to follow a DTO approach (@uk2k05) base on the following aspects:
- It allows me to keep a very clean architecture.
- This approach is more in line with the single Responsibility principle
- It ensures that my application layer isn't dependent upon an underlying domain model.
I have to acknowledge the other interesting approaches raised here, such as the Factory Pattern(@Liam) and command-query separation (CQS)(@L-Four), both of them are useful to deal with the problem but they could add extra complexity and work to my specific environment. CQS and FP require a mind shift for defining the architecture (from my humble and personal opinion).