Search code examples
c#asp.net-mvclinqiqueryableselectlistitem

Cannot implicitly convert type 'System.Linq.IQueryable<System.Web.Mvc.SelectListItem>' to 'System.Web.Mvc.SelectList'


I have a method in my controller:

private void ConfigureViewModel(EngineOIRemovalsViewModel model)
{                     
    model.MajSecList = db.EngineOIRFRs.Select(m => new SelectListItem { Value = m.MajorSection.ToString(), Text = m.MajorSection });
    if (model.SelectedMajorSection != null)
    {
        IEnumerable<EngineOIRFR> Areas = db.EngineOIRFRs.Where(l => l.MajorSection == model.SelectedMajorSection);
        model.AreaList = new SelectList(Areas);
    }
    else
    {
        model.AreaList = new SelectList(Enumerable.Empty<SelectListItem>());
    }
    if (model.SelectedArea != null)
    {
        IEnumerable<EngineOIRFR> SubAreas = db.EngineOIRFRs.Where(l => l.Area == model.SelectedArea);
        model.SubAreaList = new SelectList(SubAreas);
    }
    else
    {
        model.SubAreaList = new SelectList(Enumerable.Empty<SelectListItem>());
    }
    if (model.SelectedArea != null)
    {
        IEnumerable<EngineOIRFR> Failures = db.EngineOIRFRs.Where(l => l.SubArea == model.SelectedSubArea);
        model.FailureList = new SelectList(Failures);
    }
    else
    {
        model.FailureList = new SelectList(Enumerable.Empty<SelectListItem>());
    }
}

And I'm getting an error, from the title, in the below line:

model.MajSecList = db.EngineOIRFRs.Select(m => new SelectListItem { Value = m.MajorSection.ToString(), Text = m.MajorSection });

It says an explicit conversion exists for this, but so far my searching hasn't been able to find one. Any idea on how to solve this?


Solution

  • You have two problems (at least)

    First, you are also not Selecting the right type. MajSecList is of type SelectList, but you are explicitly selecting SelectListItem. You will need to update your Select.

    Second, Select is not executed right away. You need to use something like ToList or FirstOrDefault (depending on what you need) to actually execute the query and return the result:

    model.MajSecList = db.EngineOIRFRs.Select(m => new SelectListItem { Value = m.MajorSection.ToString(), Text = m.MajorSection }).ToList();
    

    The idea is that you can build a query, chaining together operations like Select or Where, etc. without performing the query each time.

    Once you're done building your query and use FirstOrDefault or ToList (or others), it actually performs the query and returns the results.

    Or just do what you're doing below that, and pass the query to the constructor of SelectList:

    model.MajSecList = new SelectList(db.EngineOIRFRs.Select(m => new SelectListItem { Value = m.MajorSection.ToString(), Text = m.MajorSection }));