SQL Server EF.Functions.Contains with more than one property references

bmp9r5qi  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(81)

I want to use SQL Server's Full Text Search CONTAINS through EF.Functions.Contains for doing full text search in my database.

Everything works fine with one parameter as property reference but I can find no way to use more than one property reference.

C# code with one property reference:

var test = await dbContext.MyTable.Where(x => EF.Functions.Contains(x.Column1, searchText)).ToListAsync();

Will be successfully translated to sql code like bellow:

select * from MyTable where contains(Column1 , N'SearchText')

But how can I write a C# code which give me the bellow sql code:

select * from MyTable where contains((Column1, Column2) , N'SearchText')

This way doesn't work:

Expression<Func<MyTable, object>>[] propertyReferences =  { x => x.Column1 , x=> x.Column2 }; 
var test = await dbContext.MyTable.Where(x => EF.Functions.Contains(propertyReferences, searchText)).ToListAsync();

And also this way doesn't work:

var test = await dbContext.MyTable.Where(x => EF.Functions.Contains(new {x.Column1 , x.Column2 }, searchText)).ToListAsync();
noj0wjuj

noj0wjuj1#

Like already mentioned in the comments above you need to combine the two method calls for every column. in this way you can combine as much columns as you want.

with a logical AND

var test = await dbContext.MyTable.Where(x => EF.Functions.Contains(x.Column1, searchText) && EF.Functions.Contains(x.Column2, searchText)).ToListAsync();

with a logical OR

var test = await dbContext.MyTable.Where(x => EF.Functions.Contains(x.Column1, searchText) || EF.Functions.Contains(x.Column2, searchText)).ToListAsync();

相关问题