Search code examples
c#asp.net-mvclinqentity-framework

Only parameterless constructors and initializers are supported in LINQ to Entities - MVC / C#


I am changing my Linq-to-Sql application to EF 6.1, generate the ViewData using:

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));
        }

In Controller:

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

In the View: @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;
        }
}

I get this error:

Only parameterless constructors and initializers are supported in LINQ to Entities

Would appreciate your suggestions.


Solution

  • As the error says only parameterless constructors or initializers are allowed in the query, so you should change your LINQ query.

    Try this:

    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));
    }
    

    We are executing the query first here and on.y after that we're building your KeyValuePairs. An alternative approach is to use a Dictionary (via ToDictionary LINQ method) and return this Dictionary to a calling function