Pregunta

I have to search an Entity by some values, the ones empty I don't have to consider them but the others I have to use a LIKE statement using Linq to Entities.

The result I want to obtain should be similar to this SQL,

...
WHERE
(@taxid  = '' OR  m.taxid LIKE @taxid + '%') AND  
(@personalid  = '' OR  m.personalid LIKE @personalid + '%') AND  
(@certificate  = '' OR  m.certificate LIKE @certificate + '%')

My Linq to Entities looks like:

persons = context.Persons.Where(e => e.TaxId.Contains(taxId) && e.PersonalId.Contains(personalId) && e.Certificate.Contains(certificate)).ToList();

Any clue?

¿Fue útil?

Solución

You can include parameter checking into query

from p in context.Persons
where (taxId == "" || p.TaxId.StartsWith(taxId)) &&
      (personalId == "" || p.PersonalId.StartsWith(personalId)) &&
      (certificate == "" || p.Certificate.StartsWith(certificate))
select p

Or build query dynamically

IQueryable<Person> query = context.Persons;

if (taxId != "")
   query = query.Where(p => p.TaxId.StartsWith(taxId));

if (personalId != "")
   query = query.Where(p => p.PersonalId.StartsWith(personalId));

if (certificate != "")
   query = query.Where(p => p.Certificate.StartsWith(certificate));

// etc
var people = query.ToList();

Consider also to use String.IsNullOrEmpty to verify if parameter has value.

If you need to generate LIKE '%' + @param + '%' query, then use Contains instead of StartsWith.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top