What Malcolm Frexner is saying is a nice clean way to solve your problem but can be greatly simplified using AutoMapper.
Say you have an Adapter that you are pulling DTO objects from (or if you aren't using WCF if you are pulling it directly from the database, the same concept applies)
public class AccountServiceAdapter
{
private List<Accounts> _accounts
{
get
{
if(HttpContext.Current.Cache["accounts"] == null)
HttpContext.Current.Cache["accounts"] = default(List<Accounts>());
return (List<Accounts>)HttpContext.Current.Cache["accounts"];
}
set
{
HttpContext.Current.Cache["accounts"] = value;
}
}
public List<AccountViewModel> FetchAccounts()
{
if(_accounts == default(List<Accounts>))
{
//Do Fetch From Service or Persistence and set _accounts
}
return _accounts.Select(x => x.ConvertToViewModel()).ToList();
}
}
Well that's your caching piece which you likely already have written. The next bit is where you get to have a bit of fun. I won't explain all the mapping fun of AutoMapper because there's a billion links that do it but I'll give you some snippets to get you going.
https://github.com/AutoMapper/AutoMapper/wiki/Projection
You will need to make a ProjectionManager class after you have added a reference to AutoMapper using NuGet.
public static class ProjectionManager
{
ProjectionManager()
{
//The mapping exercise is AS SIMPLE as this if all you are doing is
//using the exact same property names, it'll autowire
//If you use different projections you can create complex maps see the link
//above.
Mapper.CreateMap<Account,AccountViewModel>();
Mapper.CreateMap<AccountViewModel,Account>();
}
//Make yourself some handy extension methods for syntactic sugar
public static AccountViewModel ConvertToViewModel(this Account x)
{
return Mapper.Map<Account,AccountViewModel>(x);
}
//Make yourself some handy extension methods for syntactic sugar
public static Account ConvertFromViewModel(this AccountViewModel x)
{
return Mapper.Map<AccountViewModel,Account>(x);
}
}
After you have done all of this your caching is now crazy simple and to boot you can cast your data into view models that have all the neat features like Validation, Display Names, etc without having to clutter up your Entity objects or your DTO object out of your WCF service!