dynamic linq query with or and like - entity-framework

Let's suppose i have a list which contains strings. This list size is not known at compilation time.
List<String> liste = new List<String>
liste.Add("value1");
liste.Add("value2");
liste.Add("value3");
There is the SQL query i want to write:
SELECT * FROM MyTable
WHERE myfield LIKE '%value1%'
OR myfield LIKE '%value2%'
OR myfield LIKE '%value3%'
Here is what i wrote with Entity Framework and linq:
dbcontext.MyTable.Where(r => r. myfield.Contains(liste[0]) || r. myfield.Contains(liste[1]) || r. myfield.Contains(liste[2]));
My question is how can i iterate because my list wont contains 3 elements...
Thanks

you can do something like below in your code
var res = dbcontext.MyTable.Where(r => liste.Any(val=>val == r.myfield));

Related

Use array of ints parameter in FromSQL query and Where In clause

I have a list of ints:
var ids = new List { 10, 20 };
And I need to find Users with that ids:
context.Users.FromSqlInterpolated($#"
select Users.*
where Users.Id in ({String.Join(',', ids)})"
But I get the following error:
'Conversion failed when converting the nvarchar value '10, 20' to data type int.'
How can I use such a parameter?
Using Interpolated method is not appropriate here, because {String.Join(',', ids)} defines single string placeholder, hence EF Core binds single nvarchar parameter with value '10,20', so the actual SQL is like this
select Users.*
where Users.Id in ('10,20')
which is invalid, hence the exception.
You should use Raw method instead. Either
var query = context.Users.FromSqlRaw($#"
select Users.*
where Users.Id in ({String.Join(',', ids)})");
which will embed literal values
select Users.*
where Users.Id in (10,20)
or if you want to parameterize it, generate parameter placeholders like {0}, {1} etc. inside the SQL and pass values separately:
var placeholders = string.Join(",", Enumerable.Range(0, ids.Count)
.Select(i => "{" + i + "}"));
var values = ids.Cast<object>().ToArray();
var query = context.Users.FromSqlRaw($#"
select Users.*
where Users.Id in ({placeholders})", values);
which would generate SQL like this
select Users.*
where Users.Id in (#p0,#p1)
If you need to combine .FromSql() and SQL WHERE x IN () then perform a second operation on the output IQueryable<T> of the .FromSql() call.
var ids = new List { 10, 20 };
var query = context.Users.FromSqlInterpolated(
$#"select *
from Users");
if (ids?.Count > 0)
{
query = query.Where(user => ids.Contains(user.Id));
}
Resultant SQL approximates to:
select * from (
select *
from Users
) u
where u.Id in (10,20)
No invalid SQL if ids is empty
No empty result if ids is empty string (I was working with a string data type)

Linq Join on Lists produces a list of duplicate data

Hi I have a puzzling issue(to me at leaast).
I am using the latest Entity Framework on NetCore 2
So I created these 2 lists like this:
var cYear = await _context.CYear
.Where(c => c.Discriminator == 'C').ToListAsync();
var modCurricula = await _context.ModCurricula
.Where(m => m.ProductionStatus == 1.ToListAsync();
Stepping through the code, I can see that the lists contain the needed data.
But I need to join the two lists together using a Linq query to get the result set that I need:
var historicalYears = (from mc in modCurricula
join cy in cYear on mc.GroupId equals cy.GroupId
where cy.CYear == 1810
select mc.ModId).ToList();
However, when I do this, I get a list of 20 rows but each row is just the same data, like this:
20384 | 04722811
20384 | 04722811
20384 | 04722811
// etc...
So I tried joining the actual entity framework DbSet objects like this:
var historicalYears = (from mc in _context.ModCurricula
join cy in _context.CYear on mc.GroupId equals cy.GroupId
where cy.CYear == 1810
select mc.ModId).ToList();
And it works! I get the results I need, not just a list of duplicates.
Is there a reason why I'm getting duplicates using the first Linq query?
Thanks!

Compare 2 fields in where statement ORMLite

Is it possible to compare 2 fields from the table in where condition in ORMLite without using where().raw(statement, args)?
SQL query looks like
select
*
from
table
where
table.f1 = table.f2
try This ... i hope Its Work For You !!!
select (case when (table.f1 = table.f2 ) then 'EQUAL' else 'NOT_EQUAL' end) as one from table
OR
SELECT * FROM table WHERE f1 LIKE 'f2';
OR
SELECT * FROM table WHERE f1 = f2;
Don't know why I missed this last time. ORM Lite doc contains the answer:
ColumnArg object is designed to compare one column against another.
QueryBuilder<Table, String> queryBuilder = tableDao.queryBuilder();
queryBuilder.where().eq(Table.f1,
new ColumnArg(Table.f2));
List<Table> results = queryBuilder.query();

Sub Query in select clause with Squeryl

I'm trying to replicate the following query usine Squeryl.
SELECT c.order_number,p.customer,p.base,(
SELECT sum(quantity) FROM "Stock" s where s.base = p.base
) as stock
FROM "Card" c, "Part" p WHERE c."partId" = p."idField";
I have the following code for selecting the Cards and Parts but I cannot see a way to add a sumation into the select clause.
from(cards, parts)((c,p) =>
where(c.partId === p.id)
select(c,p)
Any help is much appreciated!
In Squeryl, you can use any Queryable object in the from clause of your query. So, to create a subquery, something like the following should work for you:
def subQuery = from(stock)(s => groupBy(s.base) compute(sum(s.quantity)))
from(cards, parts, subquery)((c, p, sq) =>
where(c.partId === p.idField and sq.key === p.base)
select(c.orderNumber, p.customer, sq.measures))
Of course the field names may vary slightly, just guessing at the class definitions. If you want the whole object for cards and parts instead of the single fields from the original query - just change the select clause to: select(c, p, sq.measures)

Search database using Entity Framework. LIKE operator

I want to search one of my tables using Entity Framework 5. I don't know how many words there are in the query, but I want to match all of them.
query = hello
SELECT * FROM [table] WHERE [column] LIKE '%hello%'
query = hello world
SELECT * FROM [table] WHERE [column] LIKE '%hello%' AND [column] LIKE '%world%'
I know the function PATINDEX , but it doesn't work good enough. Why? I'll show you:
SELECT * FROM person WHERE PATINDEX('%test%.com%', email)>0
will match "test#email.com", but if the search word are ordered the other way, it will not find this person:
SELECT * FROM person WHERE PATINDEX('%.com%test%', email)>0
What is the most efficient way to create this query using EF?
using linq to entities you can use .Contains to do the equivilant in SQL
table(x => x.column).Where(y => y.ColumnName).Contains("hello");
Sorry forgot the where clause that should work.
You can build the query in a foreach loop:
var words = new[] {"com", "test"};
var table = <your initial DbSet or ObjectSet>
foreach (var word in words)
{
string word1 = word; // prevent modified closure.
table = table.Where(x => x.column.Contains(word1));
}
var result = table.ToList(); // Enumerate the composed linq query.
The Contains function translates to LIKE with the search term enclosed in % characters.