Reputation: 33
Struggling to get this right.
So I have a model view which has an IEnumerable<selectlistitem> BusinessUnits
to bind a listBox with multiselect for the view and I have IEnumerable<string> selectedBusinessUnit
to hold the selected values.
Once the multiple values are selected and postback to the controller I am struggling to use linq query to check values in database against the IEnumerable<string> selectedBusinessUnit
. More like a SQL "IN" query.
This is my code:
public class ProjectsSearchViewModel
{
public IEnumerable<string> selectedBusinessUnit { get; set; } //Selected Revenue Organization (Business Unit)
[Display(Name = "Business Unit")]
public IEnumerable<SelectListItem> BusinessUnits { get; set; } //populate list of business units from database for the listbox
}
// My View
@Html.LabelFor(m => m.BusinessUnits, new { @class = "col-md-4 control-label" })
@Html.ListBoxFor(m => m.selectedBusinessUnit, Model.BusinessUnits, new { @class = "form-control", type = "dropdownlist", size = 5 })
// Controller
if (projectsSearchViewModel.selectedBusinessUnit != null)
{
result = result.Where(x => x.Project.Revenue_Organization.Contains(projectsSearchViewModel.selectedBusinessUnit));}
It says cannot convert IEnumerable to string
Has anyone managed to do something like this successfully. If so would be keen to know how.
More code
var results = (from project in db.Projects
join emp in db.Employees
on project.Project_Manager equals emp.Employee_ID
select new ProjectsList
{
Project = project,
Employee = emp
});
Revenue_organization is one of the columns (property if you like) in the project table (project object) in case any one is wondering. so end result i am looking for to get list of projects where revenue_organization IN selected list of businessunits
Upvotes: 3
Views: 5817
Reputation: 23827
You are using Contains on the wrong object. It would be the other way around:
result = result.Where(x =>
projectsSearchViewModel.selectedBusinessUnit.Contains(
x.Project.Revenue_Organization));
I had this assumptions:
projectsSearchViewModel.selectedBusinessUnit is an IEnumerable. x.Project.Revenue_Organization is a string value (column in db where you want to make "IN" query).
Upvotes: 1
Reputation: 62238
Assuming that Project.Revenue_Organization
is a string you need to reverse the statement. The collection should contain the string but as you have it written its checking if the string contains the collection (which does not make sense).
result = result.Where(x => projectsSearchViewModel.selectedBusinessUnit.Contains(x.Project.Revenue_Organization));}
Upvotes: 2