我正在编写使用EF-5的更新方法,并且在选择记录以进行目标更新时遇到问题。
public void Update(List<MyEntities> entitiesToUpdate)
{
// Get rows that match IDs
var findUpdateRows = this
._context
.MyEntity
.Where(w => entitiesToUpdate
.Select(s => s.SomePropertyId)
.ToList()
.Contains(w.SomePropertyId)
)
.ToList();
}
// run time error - LINQ to Entities does not recognize the method 'System.Collections.Generic.List`1[System.Int32] ToList[Int32](System.Collections.Generic.IEnumerable`1[System.Int32])' method, and this method cannot be translated into a store expression.
如果我改为尝试:
// Get rows that match IDs
var findUpdateRows = this
._context
.MyEntity
.Where(w => entitiesToUpdate
.Select(s => s.SomePropertyId)
.Contains(w.SomePropertyId)
)
.ToList();
// Run time error - Unable to create a constant value of type 'xxx.MyEntities'. Only primitive types or enumeration types are supported in this context.
使用以下代码时,我可以使方法按预期工作(但我想知道并理解如何在没有单独的idsToUpdate var和赋值的情况下完成相同的工作):
// Create list of IDs to update
List<int> idsToUpdate = new List<int>();
entitiesToUpdate.ForEach(fe => idsToUpdate.Add(fe.SomePropertyId));
// Get rows that match IDs
var findUpdateRows = this
._context
.MyEntity
.Where(w => idsToUpdate.Contains(w.SomePropertyId))
.ToList();
这个例外
无法创建类型的常量值...
始终表示在LINQ语句中的某个地方使用了对象(类实例),其中EF仅能处理原始值。所以第一步就是看:我在哪里使用对象?
var findUpdateRows = this._context.MyEntity // here
.Where(w => entitiesToUpdate // here
.Select(s => s.SomePropertyId)
.Contains(w.SomePropertyId))
现在我们知道只有一条线this._context.MyEntity
可以运行,所以应该是entitiesToUpdate
。您凭直觉就知道了。
原因是整个表达式(entitiesToUpdate
is是Expression
)被翻译成SQL,而EF根本无法将List
(类)对象翻译成SQL(只是想像一下它在SQL:/中的样子)。
所以你做对了,尽管
var idsToUpdate = entitiesToUpdate.Select(s => s.SomePropertyId).ToList();
有点短。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句