我想使用 nHhibernate 通过内存集合过滤数据库表(具有复合键 Id1 和 Id2)。
class Item{ int Id1; int Id2; }
var collection = new List<Item>();
var list = _session
.QueryOver<MyDbTable>()
.Where(x => collection.Any(y => y.Id1 == x.Id1 && y.Id2 == x.Id2))
.List();
我这样做得到的错误是“无法识别的方法调用:System.Linq.Enumerable:Boolean Any”。我也尝试使用 FirstOrDefault 方法并将结果与 null 进行比较,但它不起作用。
请您参考如下方法:
您不能在 NHibernate 中使用 Linq 方法。
如果你想验证属性是否在集合中,你可以使用 IsIn 方法,但在你的情况下我们不想检查单个属性是否在集合中,我们是寻找复合键。
要解决您的问题,您可以迭代 collection 来构造您的限制:
var disjunctionOptions = new Disjunction();
foreach (var item in collection)
{
var conjunction = new Conjunction();
conjunction.Add<MyDbTable>(x => x.Id1 == item.Id1);
conjunction.Add<MyDbTable>(x => x.Id2 == item.Id2);
disjunctionOptions.Add(conjunction);
}
var list = _session
.QueryOver<MyDbTable>()
.Where(disjuntionOptions)
.List();
有了它,您将获得使用复合键的查询的正确结果。
Note:
IsInis to check if a single property is in a colletion (or array). It will give wrong results if used separately (in each property) because you are using composite key.
