我正在开发一个应用程序,以使用不同的框架测试执行时间SQL查询。我有一些问题要使用Fluent nHibernate编写查询之一。该查询应返回所有50岁以上的员工。在某些页面中,我找到了下面附加的DateProjections类。
public static class DateProjections
{
private const string DateDiffFormat = "datediff({0}, ?1, ?2)";
public static IProjection DateDiff(
string datepart,
Expression<Func<object>> startDate,
Expression<Func<object>> endDate)
{
// Build the function template based on the date part.
string functionTemplate = string.Format(DateDiffFormat, datepart);
return Projections.SqlFunction(
new SQLFunctionTemplate(NHibernateUtil.Int32, functionTemplate),
NHibernateUtil.Int32,
Projections.Property(startDate),
Projections.Property(endDate));
}
}
获取雇员的功能如下:
public List<EmployeeAgeViewModel> GetEmployeesOlderThan50()
{
Person personAlias = null;
EmployeeAgeViewModel result = null;
var temp = _session.QueryOver<Employee>().JoinQueryOver(x => x.Person, () => personAlias).SelectList(
list => list
.Select(x => personAlias.FirstName).WithAlias(() => result.FirstName)
.Select(x => personAlias.LastName).WithAlias(() => result.LastName)
.Select(x => x.Gender).WithAlias(() => result.Gender)
.Select(x => x.BirthDate).WithAlias(() => result.BirthDate)
.Select(x => x.HireDate).WithAlias(() => result.HireDate)
.Select(DateProjections.DateDiff("yy", () => personAlias.Employee.BirthDate, () => DateTime.Now)).WithAlias(() => result.Age)
)
.TransformUsing(Transformers.AliasToBean<EmployeeAgeViewModel>())
.List<EmployeeAgeViewModel>();
return temp.ToList();
问题可能是我将BirthDate属性和DateTime.Now传递给DateDiff函数的方式。在personAlias变量中,Employee属性为空-也许我应该以某种方式对其进行分配-任何帮助将不胜感激。
答案 0 :(得分:1)
您需要使用personAlias.Employee.BirthDate
来代替employeeAlias
。
您的代码进行了必要的更改,如下所示:
Person personAlias = null;
Employee employeeAlias = null;
EmployeeAgeViewModel result = null;
var temp = _session.QueryOver<Employee>(() => employeeAlias)
.JoinQueryOver(x => x.Person, () => personAlias)
.SelectList(
list => list
.Select(x => personAlias.FirstName).WithAlias(() => result.FirstName)
.Select(x => personAlias.LastName).WithAlias(() => result.LastName)
.Select(x => x.Gender).WithAlias(() => result.Gender)
.Select(x => x.BirthDate).WithAlias(() => result.BirthDate)
.Select(x => x.HireDate).WithAlias(() => result.HireDate)
.Select(DateProjections.DateDiff("yy", () => employeeAlias.BirthDate, () => DateTime.Now))
.WithAlias(() => result.Age)
)
.TransformUsing(Transformers.AliasToBean<EmployeeAgeViewModel>())
.List<EmployeeAgeViewModel>();
return temp.ToList();