我正在尝试实现where linq表达式,它将允许我根据年份提取数据,而months.The错误在我的上下文的where方法中抛出。
我当前收到错误消息
System.NotSupportedException: 'Unable to create a constant value of type 'System.Tuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only primitive types or enumeration types are supported in this context.'Linq表达式
var periodTuples = period.ToList() // gives you List<KeyValuePair<int, int[]>>
.SelectMany(kvp =>
kvp.Value.Select(it2 => Tuple.Create(kvp.Key, it2))).ToHashSet(); // to optimize .Contains()
benchmark1Returns = GetViewService<MV_INDEX_PERFORMANCE>()
.Where(x => x.Mtd != null && x.IndexId == benchMark1 && periodTuples.Contains(Tuple.Create(x.PriceDate.Year, x.PriceDate.Month))).Select(x => x.Mtd);Where方法在我上下文中定义
public IEnumerable<T> Where(Expression<Func<T, bool>> predicate)
{
try
{
using (new TimedLogger(_perfLogger, GetCompletedText("Where")))
{
return Authorize(_repo.Where(predicate).ToList(), AuthAccessLevel.Read);
}
}
catch (Exception ex)
{
_logger.Error(ex);
throw;
}
}发布于 2019-04-24 16:27:03
EF6不支持(无法转换为SQL) Tuple.Create (和Tuple<>构造函数)、内存中集合联接、非原语类型上的内存中集合的Contains以及许多其他类型。
在您的示例中,解决方案是使用基本类型表达式替换(int year,int month) pair,如下所示:
int period = 12 * year + (month - 1)并将其用于过滤,例如
var periods = period.ToList() // gives you List<KeyValuePair<int, int[]>>
.SelectMany(kvp => kvp.Value, (year, month) => 12 * year + (month - 1));然后在LINQ查询中
periods.Contains(12 * x.PriceDate.Year + (x.PriceDate.Month - 1))请注意,在LINQ to Entities查询中,periods不需要是HashSet<int> (或List<int>等)- IEnumerable<int>就足够了,因为它将在本地计算一次并转换为SQL IN (val1, val2, ..., valN)标准。
https://stackoverflow.com/questions/55673145
复制相似问题