I have a table whose name is Table1 and the column name are Id, Name, and Description. The table stracture is:
Table1:
Id - Name - Description
1 - apple1 - It is sweet
2 - apple2 - It is sour
3 - apple3 - It is sweet and sour
I want to filter data from Table1 using EF. If the search keyword is apple1 then I will want to compare that keyword in all columns. Like as
Table1.Whare(x => x.Id == keyword || x.Name == keyword || x.Description == keyword)
Is it possible in Ef core? Please help me.
CodePudding user response:
Yes, you can do it using EF. Just a little improvement, with the fields Name
and Description
you may want to search by the operator Contains
instead because their type's string (you may encounter the situation with uppercase and lowercase)
Table1.Where(x => x.ID == keyword
|| x.Name.Contains(keyword)
|| x.Description.Contains(keyword))
CodePudding user response:
First step is to get all the columns for the table model:
var columns = typeof(MyModel).GetProperties();
Search through all the columns if it contains the keyword:
var results = dbContext.Table1.Where(x => columns.Any(
prop => prop.GetValue(x, null).ToString().Contains(keyword)))
.ToList();
Search through all the columns if it equals the keyword:
var results = dbContext.Table1.Where(x => columns.Any(
prop => prop.GetValue(x, null) == keyword))
.ToList();