I'm looking to incorporate property value translations into my QueryOver queries.
I like writing queries following the Query Object Pattern, directly producing MVC view models. In my view models, I try to use property types that are as simple as possible, keeping conversion complexity out of the views and controllers. This means that sometimes, I'll need to convert one type into another, such as dates into strings.
One could argue that such conversions should be performed in views but since most of my view models are directly translated to JSON objects, that would cause the conversion to become much more cumbersome. Performing date to string conversion in JavaScript is problematic at best and my JSON convertor is not flexible enough.
Here's an example of what I'm doing:
// Entity.
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public DateTimeOffset DateCreated { get; set; }
}
// View model.
public class CustomerViewModel
{
public string Name { get; set; }
public string DateCreated { get; set; } // Note the string type here.
}
// Query.
CustomerViewModel model = null;
List<CustomerViewModel> result = Session.QueryOver<Customer>()
.SelectList(list => list
.Select(n => n.Name).WithAlias(() => model.Name)
.Select(n => n.DateCreated).WithAlias(() => model.DateCreated))
.TransformUsing(Transformers.AliasToBean<CustomerViewModel>());
.Future<CustomerViewModel>()
.ToList();
When running the query code, the following exception is thrown:
Object of type 'System.DateTimeOffset' cannot be converted to type 'System.String'.
Obviously, this is because of the following line:
.Select(n => n.DateCreated).WithAlias(() => model.DateCreated))
So the question is: how to incorporate the date to string conversion into the query?
I don't want to perform the conversion after the query has executed because I would need an additional intermediate class to store the results before converting them.