The Entity Framework does not support all queries. This becomes obvious if you think of something like the following
dataContext.Persons.Where(person => MyMethod(person));
with MyMethod()
returning a Boolean value. The method might do everything and you cannot translate everything into SQL. The solution is to get all entities into local memory using ToList()
and then use LINQ to Object.
dataContext.Persons.ToList().Where(person => MyMethod(person));
It depends on your actual query if it can be rewritten, so that it can be transformed into SQL by the Entity Framework or if you have to do the query in local memory using LINQ to Object.
The exception you mentioned sound like you are trying something like the following.
Company company = datacontext.Companies.Where(company.Name == "ACME").Single();
dataContext.Employees.Where(employee => employee.Company == company);
LINQ to Entity does not support expressions containing entities, hence the comparison of the Company
entities is not valid. In this case you can rewrite it as follows.
dataContext.Employees.Where(employee => employee.Company.Id == company.Id);
This compares only the ids - a primitive type like a integer or a GUID - and this can be transformed into SQL.
Example for search word by word (see also the comments)
IQueryable<People> result = entities.People;
foreach (String item in searchList)
{
// This copy is important in order not to modify the closure.
String itemCopy = item;
result = result.Where(p =>
p.FirstName.ToUpper().Contains(itemCopy) ||
p.LastName.ToUpper().Contains(itemCopy) ||
p.Phone.ToUpper().Contains(itemCopy));
}
This will construct the query word by word. Noted that the Entity Framework recognizes ToUpper()
, ToLower()
, and Contains()
(and some more) - so I was to strict when I said that the Entity Framework does not recognize method calls. It does, but not many and not ToUpperInvariant()
and ToLowerInvariant()
. Further this query translates into CHARINDEX()
function calls using the collation of the column, hence the search can be case insensitive without explicit ToUpper()
or ToLower()
calls.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…