LINQ to Entities无法识别方法'System.Collections.Generic.Dictionary`

时间:2015-07-29 13:42:41

标签: c# .net linq entity-framework generics

我有这个错误的时间错误异常

LINQ to Entities does not recognize the method
 'System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.List`1[Project.Model.Value]]
ToDictionary[Value,String,List`1](System.Collections.Generic.IEnumerable`1[Project.Model.Value],
System.Func`2[Project.Model.Value,System.String],
System.Func`2[Project.Model.Value,System.Collections.Generic.List`1[Project.Model.Value]])'
method, and this method cannot be translated into a store expression.

我尽力修复它但没用。我认为来自列表的异常可以帮助我解决问题

public IEnumerable<ItemManagement> getItemsForFormType(string formType)
        {
            using (var db = new AthenaContext())
            {

                List<Value> dropDownListValue = (from val in db.Values
                                                 where val.ParentId == (from va in db.Values
                                                                        where
                                                                            va.ParentId
                                                                            == (from value3 in db.Values
                                                                                where value3.Name == formType
                                                                            select value3.RecordId).FirstOrDefault()
                                                                    select va.RecordId).FirstOrDefault()
                                             select val).ToList();
            var result = (from value1 in db.Values
                          where value1.Name == formType
                          select
                              new ItemManagement
                              {

                                  FormType = value1.Name,
                                  RecordID = value1.RecordId,
                                  FormControllerNames =
                                  (from va in db.Values
                                   where va.ParentId == (from value3 in db.Values where value3.Name == formType select value3.RecordId).FirstOrDefault()
                                   select va).ToDictionary(va => va.Name, va => dropDownListValue)
                              }).ToList();
            return result;
        }

1 个答案:

答案 0 :(得分:3)

您正在尝试将.NET库函数嵌入到EF查询中。因为它不能翻译成SQL,所以不支持。

您必须重写查询,而不使用.ToDictionary()。

这种特殊情况可能并不难。如果根本需要投影ToDictionary(),请重新访问。您可以使用以下方法安全地编写SQL可翻译投影:

.Select( new { anyName: <expression>, otherName: <otherExpression>, etc })