简体   繁体   中英

Why my LINQ Where clause concatenating a string and call 'contains' using a value is not working?

I am trying to filter data from db using two columns.

The thing is that the user only posts a single field, and I will use that field to check if there is any record on database that concatenating both columns values exist.

At the moment I have the following:

query
  .Where(x => string
     .Concat(x.Field1, " ", x.Field2)
     .Contains(parameter.MyValue, StringComparison.InvariantCultureIgnoreCase)); 

My problem is that the data is not being filtered this is weird, does anyone knows what is happening? thank you!

You did not mention which your db provider is. But you could try this:

query
  .Where(x => 
      ((x.Field1 ?? "") + " " + (x.Field2 ?? "")).Contains(parameter.MyValue)); 

This code assumes your parameter and its MyValue property are both not null, and the latter is also not empty.

Because your LINQ provider knows nothing about the Concat method. Try the same with the + operator.

First thing to check is ensure that the Sql (I assume you are querying a relational database) being generated is working when run directly against the database.

You could get the Sql statement either using a profiler, during a debug session in Visual Studio you may be able to get it via a trace, or my preference is to use LinqPad. Try these methods also.

Your query looks correct, I was able to get it to return results from my database.

Alternative queries:

query
  .Where(x => x.Field1.Contains(parameter.MyValue) || x.Field2.Contains(parameter.MyValue));


query.Select(x => new 
                  { 
                    Field = string.Concat(x.Field1, " ", x.Field2), 
                    RowData = x 
                  })
     .Where(x => x.Field.Contains(parameter.MyValue));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM