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

问题描述 投票:0回答:2

我正在将 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();

在视图中: @函数{

    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

非常感谢您的建议。

c# asp.net-mvc linq entity-framework
2个回答
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));
}

我们首先在此处执行查询,然后在y上执行查询,然后构建您的KeyValuePairs。另一种方法是使用字典(通过

ToDictionary
LINQ 方法)并将该字典返回给调用函数


0
投票

Con AsEnumerable se arregla todo,

 var b = (from type in db.OhaType
    where type.Disabled == false
    orderby type.Name
    select new {Key = type.OhaTypeId, Name = type.Name})

return b.AsEnumerable().Select(type => new KeyValuePair<int, string>(type.Key, type.Name)
© www.soinside.com 2019 - 2024. All rights reserved.