Problem
I use linq to return a list of anonymous objects
from s in _subsidiaryService.Repository.Query()
where s.Title.ToLower().Contains(term) ||
s.Description.ToLower().Contains(term) ||
s.District.ToLower().Contains(term)
select new
{
label = s.Title
,
desc = s.Description
,
value = s.ID
,
icon = Url.Content(Path.Combine(string.Format(Constants.RelativePathSubsidiary, s.ID), SmallIconFileName)) //Problem line!!
}
The line icon is where the problem is
Linq to Entities does not recognize Path.Combine or string.Format
Questions
I have two questions:
- How can I run and Path.Combine string.format inside my queries
- How do I create functions that run inside my queries? e.g:
Code sample
from s in _subsidiaryService.Repository.Query()
where s.Title.ToLower().Contains(term) ||
s.Description.ToLower().Contains(term) ||
s.District.ToLower().Contains(term)
select new
{
label = s.Title
,
desc = s.Description
,
value = s.ID
,
icon = getIconPath(s.SmallIconFileName)
}
My method
public string getIconPath(Guid id, sring fileName) {
return Url.Content(Path.Combine(string.Format(Constants.RelativePathSubsidiary, id), fileName));
}
Change it to:
The
.AsEnumerable()switches it from the query to in memory operations, so it doesn’t try to map the functions to the database.Its worth noting though that this means it runs everything up to the
.AsEnumerableon the database, pulls it locally to anIEnumerablethen starts iterating it to do the anonymous object creation. So there are performance implications to doing this. It may be worthwhile to trim the columns you are selecting by using an anonymous object or making sure all of yourWherefiltering is done prior to theAsEnumerable.