Imagine you have an application with the domain object User
:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public bool Premium { get; set; }
public int OrdersNumber { get; set; }
}
Your application has 3 views:
- the first one must show id, name and surname of all the users
- the second one must show name and surname of a user, and if he’s a premium user
- the last one must show name, surname and number of orders of a user
So I would call 3 different queries on my db:
- the first one that loads
Id
,Name
andSurname
of all the users - the second one that loads
Name
,Surname
andPremium
starting from an id - the third one that loads
Name
,Surname
andOrdersNumber
starting from an id
The problem is when I map the result of the queries to a User
object:
- in the first case I would obtain objects with
Premium=false
andOrdersNumber=0
- in the second case I would obtain an object with
OrdersNumber=0
- in the third case I would obtain an object with
Premium=false
These data are not correct, they’ve simply set to their default value.
So what should I to do?
- I can ignore the problem, and use the properties only when I know that their values have been loaded
- I can modify
Premium
andOrdersNumber
in order to accept null value (the problem of this solution is that maybeUser
objects (on domain) have alwaysPremium
andOrdersNumber
data, so the class doesn’t respect domain rules.):
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public bool? Premium { get; set; }
public int? OrdersNumber { get; set; }
}
- everytime I need users data, I load all the fields, even the ones I don’t kneed.
The problem of this solution is the waste of time and memory.
Which is the best solution?