考虑这个愚蠢的域:
namespace TryHibernate.Example
{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class WorkItem
{
public int Id { get; set; }
public string Description { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
public class Task
{
public int Id { get; set; }
public Employee Assignee { get; set; }
public WorkItem WorkItem { get; set; }
public string Details { get; set; }
public DateTime? StartDateOverride { get; set; }
public DateTime? EndDateOverride { get; set; }
}
}
这个想法是,每个工作项目都可以分配给具有不同详细信息的多个员工,可能会覆盖工作项目本身的开始/结束日期。如果这些覆盖为空,则应取而代之的是从工作项中获取它们。
现在我想执行一个对有效 日期有限制的查询。我先试过这个:
IList<Task> tasks = db.QueryOver<Task>(() => taskAlias)
.JoinAlias(() => taskAlias.WorkItem, () => wiAlias)
.Where(() => taskAlias.StartDateOverride.Coalesce(() => wiAlias.StartDate) <= end)
.And(() => taskAlias.EndDateOverride.Coalesce(() => wiAlias.EndDate) >= start)
.List();
不幸的是,它无法编译,因为 Coalesce
需要一个常量,而不是一个属性表达式。
好的,我试过了:
.Where(() => (taskAlias.StartDateOverride == null
? wiAlias.StartDate
: taskAlias.StartDateOverride) <= end)
.And(() => (taskAlias.EndDateOverride == null
? wiAlias.EndDate
: taskAlias.EndDateOverride) >= start)
这会抛出 NullReferenceException。不知道为什么,但可能是因为 NHibernate 没有正确翻译该三元运算符(并试图实际调用它)或者因为 == null
不是检查空值的正确方法。不管怎样,我什至没想到它会起作用。
最后,这个成功了:
IList<Task> tasks = db.QueryOver<Task>(() => taskAlias)
.JoinAlias(() => taskAlias.WorkItem, () => wiAlias)
.Where(Restrictions.LeProperty(
Projections.SqlFunction("COALESCE", NHibernateUtil.DateTime,
Projections.Property(() => taskAlias.StartDateOverride),
Projections.Property(() => wiAlias.StartDate)),
Projections.Constant(end)))
.And(Restrictions.GeProperty(
Projections.SqlFunction("COALESCE", NHibernateUtil.DateTime,
Projections.Property(() => taskAlias.EndDateOverride),
Projections.Property(() => wiAlias.EndDate)),
Projections.Constant(start)))
.List();
但我无法调用干净的代码。也许我可以将某些表达式提取到单独的方法中以稍微清理一下,但使用表达式语法而不是这些丑陋的投影会好得多。有办法吗? NHibernate 不支持 Coalesce
扩展中的属性表达式有什么原因吗?
一个明显的替代方法是选择所有内容,然后使用 Linq 或其他工具过滤结果。但这可能会成为总行数很大的性能问题。
这里是完整的代码,以防有人想尝试:
using (ISessionFactory sessionFactory = Fluently.Configure()
.Database(SQLiteConfiguration.Standard.UsingFile("temp.sqlite").ShowSql())
.Mappings(m => m.AutoMappings.Add(
AutoMap.AssemblyOf<Employee>(new ExampleConfig())
.Conventions.Add(DefaultLazy.Never())
.Conventions.Add(DefaultCascade.All())))
.ExposeConfiguration(c => new SchemaExport(c).Create(true, true))
.BuildSessionFactory())
{
using (ISession db = sessionFactory.OpenSession())
{
Employee empl = new Employee() { Name = "Joe" };
WorkItem wi = new WorkItem()
{
Description = "Important work",
StartDate = new DateTime(2016, 01, 01),
EndDate = new DateTime(2017, 01, 01)
};
Task task1 = new Task()
{
Assignee = empl,
WorkItem = wi,
Details = "Do this",
};
db.Save(task1);
Task task2 = new Task()
{
Assignee = empl,
WorkItem = wi,
Details = "Do that",
StartDateOverride = new DateTime(2016, 7, 1),
EndDateOverride = new DateTime(2017, 1, 1),
};
db.Save(task2);
Task taskAlias = null;
WorkItem wiAlias = null;
DateTime start = new DateTime(2016, 1, 1);
DateTime end = new DateTime(2016, 6, 30);
IList<Task> tasks = db.QueryOver<Task>(() => taskAlias)
.JoinAlias(() => taskAlias.WorkItem, () => wiAlias)
// This doesn't compile:
//.Where(() => taskAlias.StartDateOverride.Coalesce(() => wiAlias.StartDate) <= end)
//.And(() => taskAlias.EndDateOverride.Coalesce(() => wiAlias.EndDate) >= start)
// This throws NullReferenceException:
//.Where(() => (taskAlias.StartDateOverride == null ? wiAlias.StartDate : taskAlias.StartDateOverride) <= end)
//.And(() => (taskAlias.EndDateOverride == null ? wiAlias.EndDate : taskAlias.EndDateOverride) >= start)
// This works:
.Where(Restrictions.LeProperty(
Projections.SqlFunction("COALESCE", NHibernateUtil.DateTime,
Projections.Property(() => taskAlias.StartDateOverride),
Projections.Property(() => wiAlias.StartDate)),
Projections.Constant(end)))
.And(Restrictions.GeProperty(
Projections.SqlFunction("COALESCE", NHibernateUtil.DateTime,
Projections.Property(() => taskAlias.EndDateOverride),
Projections.Property(() => wiAlias.EndDate)),
Projections.Constant(start)))
.List();
foreach (Task t in tasks)
Console.WriteLine("Found task: {0}", t.Details);
}
}
配置非常简单:
class ExampleConfig : DefaultAutomappingConfiguration
{
public override bool ShouldMap(Type type)
{
return type.Namespace == "TryHibernate.Example";
}
}
最佳答案
让我们从这里开始:
// This doesn't compile:
//.Where(() => taskAlias.StartDateOverride.Coalesce(() => wiAlias.StartDate) <= end)
//.And(() => taskAlias.EndDateOverride.Coalesce(() => wiAlias.EndDate) >= start)
并将其修改为:
.Where(() => taskAlias.StartDateOverride.Coalesce(wiAlias.StartDate) <= end)
.And(() => taskAlias.EndDateOverride.Coalesce(wiAlias.EndDate) >= start)
现在可以编译了。但在运行时它会生成相同的 NullReferenceException
。不好。
事实证明,NHibernate 确实尝试评估 Coalesce
参数。通过查看 ProjectionExtensions
类实现可以很容易地看出这一点。以下方法处理 Coalesce
转换:
internal static IProjection ProcessCoalesce(MethodCallExpression methodCallExpression)
{
IProjection projection = ExpressionProcessor.FindMemberProjection(methodCallExpression.Arguments[0]).AsProjection();
object obj = ExpressionProcessor.FindValue(methodCallExpression.Arguments[1]);
return Projections.SqlFunction("coalesce", (IType) NHibernateUtil.Object, projection, Projections.Constant(obj));
}
请注意第一个参数 (FindMemberExpression
) 与第二个参数 (FindValue
) 的不同处理方式。好吧,FindValue
只是尝试计算表达式。
现在我们知道是什么导致了这个问题。我不知道为什么要这样实现,所以会集中精力寻找解决方案。
幸运的是,ExpressionProcessor
类是公开的,还允许您通过 RegisterCustomMethodCall
/RegisterCustomProjection
方法注册自定义方法。这引导我们找到解决方案:
- 创建一个类似于
Coalesce
的自定义扩展方法(例如将它们命名为IfNull
) - 注册自定义处理器
- 使用它们代替
Coalesce
实现如下:
public static class CustomProjections
{
static CustomProjections()
{
ExpressionProcessor.RegisterCustomProjection(() => IfNull(null, ""), ProcessIfNull);
ExpressionProcessor.RegisterCustomProjection(() => IfNull(null, 0), ProcessIfNull);
}
public static void Register() { }
public static T IfNull<T>(this T objectProperty, T replaceValueIfIsNull)
{
throw new Exception("Not to be used directly - use inside QueryOver expression");
}
public static T? IfNull<T>(this T? objectProperty, T replaceValueIfIsNull) where T : struct
{
throw new Exception("Not to be used directly - use inside QueryOver expression");
}
private static IProjection ProcessIfNull(MethodCallExpression mce)
{
var arg0 = ExpressionProcessor.FindMemberProjection(mce.Arguments[0]).AsProjection();
var arg1 = ExpressionProcessor.FindMemberProjection(mce.Arguments[1]).AsProjection();
return Projections.SqlFunction("coalesce", NHibernateUtil.Object, arg0, arg1);
}
}
由于永远不会调用这些方法,因此您需要确保通过调用 Register
方法注册自定义处理器。这是一个空方法,只是为了确保在实际注册发生的地方调用类的静态构造函数。
因此在您的示例中,在开头包含:
CustomProjections.Register();
然后在查询中使用:
.Where(() => taskAlias.StartDateOverride.IfNull(wiAlias.StartDate) <= end)
.And(() => taskAlias.EndDateOverride.IfNull(wiAlias.EndDate) >= start)
它会按预期工作。
附言上面的实现适用于常量和表达式参数,因此它确实是 Coalesce
的安全替代品。
关于c# - NHibernate QueryOver 将一个属性合并到另一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38512733/