LINQ to Entities中仅支持无参数构造函数和初始值设定项 - MVC / C#

时间:2014-11-27 19:20:31

标签: c# asp.net-mvc linq entity-framework

我正在将Linq-to-Sql应用程序更改为EF 6.1,使用以下命令生成ViewData:

public IEnumerable<KeyValuePair<int, string>> GetOhaTypes ()
        {
        return (from type in db.OhaType
                where type.Disabled == false
                orderby type.Name
                select new KeyValuePair<int, string>(type.OhaTypeId, type.Name));
        }

在控制器中:

ViewData["OhaTypes"] = _vRepository.GetOhaTypes();

在视图中: @functions {

    List<SelectListItem> GetDropDownListItems (string listName, int currentValue)
        {
        var list = new List<SelectListItem>();
        var pairs = this.ViewData[listName] as IEnumerable<KeyValuePair<int, string>>;

        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

非常感谢您的建议。

1 个答案:

答案 0 :(得分:2)

由于错误说查询中只允许无参数构造函数或初始值设定项,因此您应该更改LINQ查询。

试试这个:

public IEnumerable<KeyValuePair<int, string>> 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<int, string>(type.Key, type.Name));
}

我们首先在这里和之后执行查询。之后我们正在构建您的KeyValuePairs。另一种方法是使用Dictionary(通过ToDictionary LINQ方法)并将此Dictionary返回给调用函数