开发者

Entity Framework 4.1 - How to prevent EF escaping wildcards?

开发者 https://www.devze.com 2023-03-08 22:16 出处:网络
Is there a way to tell EF not to escape my wildcards? My current solution looks like this: var movieNameWithProperWildcards = string.Format(\"%{0}%\",

Is there a way to tell EF not to escape my wildcards?

My current solution looks like this:

 var movieNameWithProperWildcards = string.Format("%{0}%",    
 movieName.ToLower().Replace("*", "%"));

 var sqlParameter = new SqlParameter { ParameterName = "searchParameter", Value =   
 movieNameWithProperWildcards };

 List<Movie&g开发者_如何学运维t; movieEntities = MovieContext.Movies.SqlQuery("select * from Movies WHERE 
 Lower(title) like @searchParameter", sqlParameter).ToList();

But that would be much nicer:

 List<Movie> movieEntities = MovieContext.Movies.Where(movie =>  
 movie.Title.ToLower().Contains(movieName));

br rene_r


You want to use LIKE so you can use either your way, ESQL or Linq-to-entities and Contains canonical function. ORM tool is not responsible for translating wildcards from your representation to wildcards representation in the database - you must do it yourselves with tools provided by ORM.

Generally this should work:

var query = from m in ctx.Movies
            where m.Name.ToLower().Contains(movieName)
            select m;

Both String.ToLower and String.Contains are in the list of supported canonical functions.


Check that the query that gets executed is right. See here how you can use context's Log to do that http://www.thereforesystems.com/view-query-generate-by-linq-to-sql/

0

精彩评论

暂无评论...
验证码 换一张
取 消