Reputation: 10679
I have a Linq query I need to use in my Index method in the page's controller, however I am getting the following error on the "select new" portion of the code:
Error
Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' to 'string'
Action method
public ActionResult Index(string query)
{
var agentProductTraining = "";
if (String.IsNullOrEmpty(query))
{
BlankIndex();
}
else
{
agentProductTraining = from course in db.Course
where
course.CourseDescription.Contains(query)
select new
{
course.CourseCode,
course.CourseDescription,
course.Partner,
course.Status,
course.LastChangeDate,
course.LastChangeOperator
};
}
return View(agentProductTraining.ToList());
}
Upvotes: 0
Views: 480
Reputation: 152556
You've initialized the variable as a string, so the compiler makes the variable a string
type (since you've user the var
keyword), but then tried to assign a collection of anonymous types to it.
You can declare it as an object
instead or var
:
object agentProductTraining; // can safely be overwritten
Also I assume you mean:
return BlankIndex();
in the if
block. Otherwise it will fall through to
return View(agentProductTraining.ToList());
where agentProductTraining
is going to be null
Of course if you use return BlankIndex
in the if
block you can simplify the whole thing:
if (String.IsNullOrEmpty(query))
{
return BlankIndex();
}
// don't need an `else` here since the if will return to the caller
var agentProductTraining = from course in db.Course
where
course.CourseDescription.Contains(query)
select new
{
course.CourseCode,
course.CourseDescription,
course.Partner,
course.Status,
course.LastChangeDate,
course.LastChangeOperator
};
return View(agentProductTraining.ToList());
Upvotes: 1
Reputation: 887433
As the error clearly states, you cannot assign the result of a LINQ query (IQueryable<T>
) to a variable of type string
.
You should declare the variable in that line:
var agentProductTraining = select ...
Upvotes: 4