LINQ to Entities中仅支持无参数构造函数和初始值设定项 – MVC / C#
我正在将我的Linq-to-Sql应用程序更改为EF 6.1,使用以下命令生成ViewData:
public IEnumerable<KeyValuePair> GetOhaTypes () { return (from type in db.OhaType where type.Disabled == false orderby type.Name select new KeyValuePair(type.OhaTypeId, type.Name)); }
在控制器中:
ViewData["OhaTypes"] = _vRepository.GetOhaTypes();
在视图中:@functions {
List GetDropDownListItems (string listName, int currentValue) { var list = new List(); var pairs = this.ViewData[listName] as IEnumerable<KeyValuePair>; if (pairs != null) { list.AddRange(pairs.Select(pair => new SelectListItem { Text = pair.Value, Value = pair.Key.ToString(CultureInfo.InvariantCulture), Selected = pair.Key == currentValue })); } return list; } }
我收到此错误:
Only parameterless constructors and initializers are supported in LINQ to Entities
非常感谢您的建议。
由于错误说在查询中只允许无参数构造函数或初始值设定项,因此您应该更改LINQ查询。
试试这个:
public IEnumerable> GetOhaTypes () { return (from type in db.OhaType where type.Disabled == false orderby type.Name select new {Key = type.OhaTypeId, Name = type.Name}).ToList() .Select(type => new KeyValuePair(type.Key, type.Name)); }
我们首先在这里和之后执行查询。之后我们正在构建你的KeyValuePairs。 另一种方法是使用Dictionary(通过ToDictionary
LINQ方法)并将此Dictionary返回给调用函数