I am using the new mvc4 ajax controller template and I don’t know how to add a search to the database query that they have.
Let’s say I have a model called Article, here is what the controller contains by default:
ObjectQuery<Article> articles = (db as IObjectContextAdapter).ObjectContext.CreateObjectSet<Article>();
articles = articles.OrderBy("it." + orderBy + (desc ? " desc" : ""));
This works fine, but I am not familial with IObjectContextAdapter and I don’t know how to add a search (ie. to see if a Article contains a term.) Normally I would have something like this:
var articles = from a in db.Articles.ToList()
select a;
if(!String.IsNullOrEmpty(search))
{
articles = articles.Where(a => a.Title.ToLower().Contains(search.ToLower())
|| a.FullArticle.ToLower().Contains(search.ToLower())
|| a.TagsAndKeywords.ToLower().Contains(search.ToLower()));
}
switch(orderBy)
{
case "TimeStamp":
if(desc)
articles = articles.OrderByDescending(a => a.TimeStamp);
else
articles = articles.OrderBy(a => a.TimeStamp);
break;
case "Title":
...
}
Obviously the new way of doing this is more succinct so I would like to stick with this. I tried combining them, using the linq query to populate the var articles, but then I am not able to use the order by part, .OrderBy(“it.” + orderBy + (desc ? ” desc” : “”)).
So my question is what is the best way to search through my database? And what exactly is this .OrderBy(“it.” + orderBy + (desc ? ” desc” : “”)) doing? I’m only familial with using OrderBy with linq.
Edit
After a lot of reading I have a better understanding of what is going on, although I still can’t get this to work.
According to this it seems like I need something similar to this:
articles = articles.Where("it.Title = @searchString");
although I think this would only work if searchString matched the title exactly. While I still don’t quite understand what this is doing, I think it uses sql expressions so I thought that this may work:
articles = articles.Where("it.Title like '%@searchString%'");
But none of this worked, and I am only shooting in the dark since I am unfamiliar with this.
The most succinct way to query your model without changing mvc4 template code is to create an IQueryable object and query it, like this:
This keep the entries in the correct order, and be sure to return the new iArticles instead of the old Articles.