Entity Framework wildcards & Linq

c# entity-framework linq odac

Question

Is it possible to construct a valid Linq query which contains wildcard characters?

I've seen various answers to this question which suggest using:

.Where(entity => entity.Name.Contains("FooBar"))
.Where(entity => entity.Name.EndsWith("Bar")) 
.Where(entity => entity.Name.StartsWith("Foo"))

OR constructing RawSql:

var commandText =
    @"SELECT field
    FROM     table
    WHERE    field LIKE @search";

var query = new ObjectQuery<Profile>(commandText, context);
query.Parameters.Add(new ObjectParameter("search", wildcardSearch));

The first solution wouldn't work if the wildcard was not at the beginning or end of a string, for example, searchTerm = "Foo%Bar".

The second solution, using RawSql, doesn't sit right with me and feels like a cheap way out. But it does work.

The third option I have yet to try out is to create something which can parse the search term and construct a valid Linq query, which is something @Slauma had a go at in link 2 below. But this still wouldn't work if the wildcard was not at the beginning or end of the search term.

So the question: Is it possible to construct a valid Linq query which contains wildcard characters?

EDIT: Its worth mentioning that in this instance im using Oracle Data Access Components (ODAC/ODP), but I don't think it makes much difference in this case.

links:

1.“like” queries in Entity Framework

2.exact and wildcard searching conditional on search term

3.Using RawSql

1
3
5/23/2017 12:24:59 PM

Popular Answer

If you are using an EDMX file as the basis for your Entity Model then perhaps you could try creating a Conceptual Model Function that then performs a LIKE in SQL. I am not sure if this would work for Oracle. You should then be able to do something like the following:

.Where(entity => Like(entity.Name, "Foo%Bar"))
2
7/18/2013 1:05:23 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow