NHibernate QueryOver 用投影填充父对象中的 属性 对象

NHibernate QueryOver fill property object in parent object with projections

我的 QueryOver 有问题,我不明白为什么。我查询 returns viewmodel 对象 ContactInfo。我在员工 属性 上收到此错误:"could not find setter for property"。如何在 ContactInfo 中填写 Employee 属性?我做错了什么?

ViewModel 对象:

public class ContactInfo    
{
    public EmployeeInfo Employee { get; set; }
    public string Email { get; set; }
    public string InternalTelephone { get; set; }
}

查询

public override ContactInfo Execute()
    {
        ContactInfo r = null;
        EmployeeInfo ei = null;

        var result = Session.QueryOver<Job>()
            .JoinAlias(j => j.EmployeeInfo, () => ei)
            .Where(j => j.EmployeeInfo.Id == _employeeId)
            .Select(
                Projections.Property<Job>(j => ei.Id).WithAlias(() => r.Employee.Id),
                Projections.Property<Job>(j => ei.FirstName).WithAlias(() => r.Employee.FirstName),
                Projections.Property<Job>(j => ei.LastName).WithAlias(() => r.Employee.LastName),
                Projections.Property<Job>(j => ei.ReferenceCode).WithAlias(() => r.Employee.ReferenceCode),
                Projections.Property<Job>(j => j.Telefoon).WithAlias(() => r.InternalTelephone)
            )
            .TransformUsing(Transformers.AliasToBean<ContactInfo>())
            .Take(1)
            .SingleOrDefault<ContactInfo>();

        var email = Session.QueryOver<Employee>()
            .Where(e => e.Id == _employeeId)
            .Select(e => e.Email)
            .SingleOrDefault<string>();

        result.Email = email;

        return result;
    }
}

我们可以做的是使用不同于 default 结果转换器,例如DeepTransformer

在那种情况下,查询必须使用类似于 DTO 模型的 Alias。因此,如果我们的域 属性 ei.FirstName 属于 JoinAlias - j.EmployeeInfo - 别名必须反映 DTO ContactInfo - "EmployeeInfo.FirstName"

.Select(        
    Projections.Property<Job>(j => ei.FirstName)         // the mapped domain model
                          .As("EmployeeInfo.FirstName"), // the path in DTO/view model
    ...
)
.TransformUsing(DeepTransformern<ContactInfo>()) // the DTO

所以现在,路径 "EmployeeInfo.FirstName" 将用于填充 Employee 作为 属性 EmployeeInfo 及其 属性 FirstName

和这个结果转换器

DeepTransformer 将使用 Alias 来构建参考树。可用于引用/many-to-one 以及 IDictionary ... (但不适用于 collections)

注意:.Is()方法来自一些扩展,可以用with != null代替

public static partial class Ext
{
    public static bool Is(this object value)
    {
        return value != null;
    }
....