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 ind开发者_运维技巧icating 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:
public void TheMethod(int accountId, string searchTerm)
{
var result = from item in ctx.Items
where item.Name.Contains(searchTerm)
let temp = new
{
Name = item.Name,
IsFavorite = item.FavoriteItems
.Any(f => f.AccountId == accountId)
}
orderby temp.IsFavorite descending, temp.Name
select temp;
}
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 searchTerm
in the name. That's probably the most expensive parts as its converted to WHERE Name LIKE %@name%
.
The .Any
call that results IsFavorite
field results in a EXISTS SELECT TOP(1)...
type of query, and should be quite cheap.
精彩评论