【发布时间】:2011-08-08 09:55:22
【问题描述】:
我希望将属性值转换合并到我的 QueryOver 查询中。
我喜欢按照查询对象模式编写查询,直接生成 MVC 视图模型。在我的视图模型中,我尝试使用尽可能简单的属性类型,将转换复杂性排除在视图和控制器之外。这意味着有时,我需要将一种类型转换为另一种类型,例如将日期转换为字符串。
有人可能会争辩说,这种转换应该在视图中执行,但由于我的大多数视图模型都直接转换为 JSON 对象,这会导致转换变得更加麻烦。在 JavaScript 中执行日期到字符串的转换充其量是有问题的,而且我的 JSON 转换器不够灵活。
这是我正在做的一个例子:
// 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();
运行查询代码时,抛出如下异常:
Object of type 'System.DateTimeOffset' cannot be converted to type 'System.String'.
显然,这是因为下面这行:
.Select(n => n.DateCreated).WithAlias(() => model.DateCreated))
所以问题是:如何将日期到字符串的转换合并到查询中?
我不想在查询执行后执行转换,因为在转换结果之前我需要一个额外的中间类来存储结果。
【问题讨论】:
标签: c# asp.net-mvc nhibernate queryover