【发布时间】:2016-04-27 08:15:43
【问题描述】:
我有一个集合(在 DbSet 中),我想按其属性(距离)的计算结果对其进行排序,并将其转换(重新使用距离)到不同的模型。每个条目只应进行一次计算(作为 DbSet,它将在数据库本身中执行)。
class InputModel {
Vector3 position;
}
class OutputModel {
double distance;
}
var inputList = getInputList(); // returns IQueryable<InputModel>
var outputList = inputList
.Where( x => (){
var dist = calculateDistance( x.position );
// calculateDistance() boils down to a simple equation that could directly translated to an sql-query (when typed in statically by hand)
return dist < maxDistance;
})
.Select( x => () {
return new OutputModel {
distance = ???; // get the calculated distance somehow
})
.ToList();
我想到了两种可能的解决方案:
- 将数据库中的所有条目放入容器中,然后计算距离并在 foreach 循环中过滤条目。
- 在转换为 OutputModel 时按距离过滤并重新计算距离。
是否可以一次性完成(最好是在数据库中计算)?
【问题讨论】:
-
1. Linq to Entities 提供商不允许您在
Where()中使用calculateDistance()。显示它的代码,以便我们知道它是否可以分解为提供者将能够翻译的东西。 2.getInputList()是否返回IQueryable<InputModel>? -
calculateDistance()是 db (SQL) 支持的一个简单的数学函数(但是我不知道它是否会直接转换为 sql-statements,我对此没有任何经验)。是的,IQueryable<InputModel>是要处理的容器。
标签: c# entity-framework linq linq-to-entities