San*_*zen 7 c# nhibernate asp.net-mvc queryover
我希望将属性值转换合并到我的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();
Run Code Online (Sandbox Code Playgroud)
运行查询代码时,抛出以下异常:
Object of type 'System.DateTimeOffset' cannot be converted to type 'System.String'.
Run Code Online (Sandbox Code Playgroud)
显然,这是因为以下几行:
.Select(n => n.DateCreated).WithAlias(() => model.DateCreated))
Run Code Online (Sandbox Code Playgroud)
所以问题是:如何将日期转换为字符串转换为查询?
我不想在执行查询后执行转换,因为在转换它们之前我需要一个额外的中间类来存储结果.
Jam*_*Ide 10
List<CustomerViewModel> result = Session.QueryOver<Customer>(() => customerAlias)
.SelectList(list => list
.Select(n => customerAlias.Name).WithAlias(() => model.Name)
// I'm not sure if customerAlias works here or why you have declared it at all
.Select(Projections.Cast(NHibernateUtil.String, Projections.Property<Customer>(c => c.DateCreated))).WithAlias(() => model.DateCreated))
.TransformUsing(Transformers.AliasToBean<CustomerViewModel>());
.Future<CustomerViewModel>()
.ToList();
Run Code Online (Sandbox Code Playgroud)
应该工作但不幸的是没有给你任何控制字符串的格式.我通过在模型上定义一个私有属性来处理类似的问题,该属性将数据保存为正确的类型,并使用字符串属性来返回格式化的值,即:
public class CustomerViewModel
{
public string Name { get; set; }
private DateTime DateCreatedImpl { get; set; }
public string DateCreated { get { return DateCreatedImpl.ToString(); }}
}
Run Code Online (Sandbox Code Playgroud)
这有几个优点,但可能不适合您的JSON转换器.您的转换器是否具有允许其忽略私有属性的设置或属性?
| 归档时间: |
|
| 查看次数: |
6421 次 |
| 最近记录: |