I’m using Entity Framework 4 in a project, and I have one specific query that gets run over and over again that I need to be sure that is optimized as good as possible.
I have one database table called Items that have the following important columns:
id (primary key)
name
Another table called FavoriteItems has two important columns
itemId (foreign key to the items table)
accountId( foreign key to the account table)
In a method in my code, I have accountId, and a searchTerm as input parameters.
The method should return all items from the items table that has searchTerm as a part of it’s name, in addition it should be sorted alphabetically, but all the items that has it’s Id found in the FavoriteItems table where the accountId match the accountId given as parameter should be put on top (and sorted alphabetically). In addition, the searhc result should contain a boolean indicating whether it’s a favorite item or not.
I have got it working, but the query seems clumsy. How would you write this query in an elegant and performant way?
I think you mean something like this:
Create an intermediate object with just the values you need, order that, and select it.
I don’t think it can be optimized further, because you need all the items that have have
searchTermin the name. That’s probably the most expensive parts as its converted toWHERE Name LIKE %@name%.The
.Anycall that resultsIsFavoritefield results in aEXISTS SELECT TOP(1)...type of query, and should be quite cheap.