c# - 如何将属性值转换合并到 NHibernate QueryOver .SelectList 中?

标签 c# asp.net-mvc nhibernate queryover

我希望将属性值转换合并到我的 QueryOver 查询中。

我喜欢按照查询对象模式编写查询,直接生成 MVC View 模型。在我的 View 模型中,我尝试使用尽可能简单的属性类型,将转换复杂性排除在 View 和 Controller 之外。这意味着有时,我需要将一种类型转换为另一种类型,例如将日期转换为字符串。

有人可能会争辩说这种转换应该在 View 中执行,但由于我的大多数 View 模型都直接转换为 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))

所以问题是:如何将日期到字符串的转换合并到查询中?

我不想在查询执行后执行转换,因为在转换之前我需要一个额外的中间类来存储结果。

最佳答案

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();

应该可以,但不幸的是,您无法控制字符串的格式。我通过在模型上定义一个将数据保存为正确类型的私有(private)属性和一个返回格式化值的字符串属性来处理类似的问题,即:

public class CustomerViewModel
{
    public string Name { get; set; }
    private DateTime DateCreatedImpl { get; set; }
    public string DateCreated { get { return DateCreatedImpl.ToString(); }}
}

这有几个优点,但可能不适用于您的 JSON 转换器。您的转换器是否具有允许其忽略私有(private)属性的设置或属性?

关于c# - 如何将属性值转换合并到 NHibernate QueryOver .SelectList 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6980397/

相关文章:

C# DateTime.ToUniversalTime() 在 C++ Win32 中

c# - c#中如何为方法添加参数注释

asp.net-mvc - ASP.NET MVC 模型绑定(bind)器问题

asp.net-mvc - Asp.Net.Mvc git 标签如何与 git 修订相关联?

c# - SSIS-如何从文本文件加载数据,而文件路径在另一个文本文件中?

c# - 在经典 ASP 上构建 .net 应用程序

asp.net-mvc - 如果用户在 int 字段中放置非数字字符串,则自定义验证错误消息

c# - 如何停止 nHibernate 以保存 View ?

c# - 具有类层次结构的 NHibernate 映射,其基类是抽象的且鉴别器不是字符串

sql - 如何将此 native SQL 查询转换为 HQL