Need multiple where conditions to a query with OR operator - c#

I have a requirement to add multiple where conditions with or operator out of which one where condition will have to check if the db column has any of the item in a list provided. Please consider the query below
var res= from table1 in context.table1
join table2 in context.table2
on table1.id equals table2.id
where table1.name=="res1" || table1.description=="desc"
|| table1.name.any(res=>FreeText.Contains(res))
select table1
this query is leading the compiler to run query multiple times and I am not getting required result. My end goal is to achieve the following sql query
select * from table1 join table2 on table1.id ==table2.id
where table1.name=="res1" || table1.description=="desc" || table1.name like "%item1%" ||table1.name like "%item2% ......"
the like statements should be dynamically added based on the items in the list.

try this...
var res= from table1 in context.table1
join table2 in context.table2
on table1.id equals table2.id
where table1.name=="res1" || table1.description=="desc"
|| FreeText.Any(p => table1.name.Contains(p, StringComparison.InvariantCultureIgnoreCase))
select table1

Related

Entity Framework / LINQ: Left join defaultifempty fails

I need to join 5 tables in a query. 3 of these tables must have relations, but two of them are optionally connected to an entry.
Because of this, I am trying to do a LEFT JOIN to Table4 and Table5 like this:
var cDesc = (cDesc == null ? "" : cDesc);
var cStreet = (cStreet == null ? "" : cStreet);
var q = await (from t1 in MyContext.Table1
join t2 in MyContext.Table2
on t1.ID equals t2.ObjectID
join t3 in MyContext.Table3
on t2.TeamID equals t3.TeamID
join t4 in MyContext.Table4
on t1.ID equals t4.ObjectID
into join3
from j3 in join3.DefaultIfEmpty()
join t5 in MyContext.Table5
on j3.StorageID equals t5.StorageID
where t2.ObjectType.Equals(16)
&& t3.UserID.Equals(userID)
&& t1.Description.Contains(cDesc)
&& l.Address.Contains(cStreet)
orderby t1.ID descending
select new Table1ListModel
{
ID = t1.ID,
Description = t1.Description,
Address = t5.Address
}
)
.Take(takeThis)
.ToListAsync();
But this query only works for rows that has a connection to Table4, so I'm doing something wrong obviously.
Am I doing the join correctly? Or is the problem that I want to run a where on address that comes from the fifth table?
Basically once you left join one table into a query any additional tables that you want to join to that one should almost always also be done with left joins. In your case you're saying you want keep rows in Table1 that don't have a match in Table4, but then you say you only want matches between Table4 and Table5 which basically will remove all the Table1 results that didn't have a match in Table4. Basically you want something like this
from j3 in join3.DefaultIfEmpty()
join temp5 in MyContext.Table5
on j3.StorageID equals temp5.StorageID into join4
from t5 in join4.DefaultIfEmpty()
This looks like a source of your problem:
join t4 in MyContext.Table4
on t1.ID equals t4.ObjectID
into join3
This means that you are inner joining Table4 to Table1

How to add || (OR) condition with linq join

How to convert the below SQL query into LINQ query for C#.net
Select t1.id,t2.Name
From table1 t1
INNER JOIN table t2
ON ((t1.column3 is null and t1.id = t2.id)
OR( t.Column3 is NOT NULL and t1.column3 = t3.Column3))
Join tblXYZ xyz on t1.column4 = xys.columnn2
I was unable to add or condition after first set up comparison in linq query, please suggest correct way to achieve this in linq.
Making some assumptions about what you meant, I would suggest hoisting the OR to a union:
(from t1 in table1
join t2 in table2 on t1.Column3 equals t2.Column3
join xyz in tblXYZ on t1.Column4 equals xyz.column2
where t1.Column3 != null).Union(
from t1 in table1
join t2 in table2 on t1.id == t2.id
join xyz in tblXYZ on t1.Column4 equals xyz.column2
where t1.Column3 == null)

Multiple table join with multiple table where clause

I have a query that's something like this.
Select a.*
from table1 a
inner join table2 b on a.field1 = b.field1
inner join table3 c on b.field2 = c.field2
where b.field4 = beta and c.field5 = gamma.
On LINQ, I tried to do that this way:
var query = (from a in table1
join b in table2 on a["field1"] equals b["field1"]
join c in table3 on b["field2"] equals c["field2"]
where (b["field4"] == beta && c["field5"] == gamma)
select a).ToList();
But for some reason, when I try to do this I get an error that says that the entity "table2" doesn't have the field Name = "field5", as though as the where clause was all about the last joined table and the other ones were unaccessible. Furthermore, the compiler doesn't seem to notice neither, because it lets me write c["field5"] == gamma with no warning.
Any ideas? Am I writing this wrong?
Thanks
See these links:
How to: Perform Inner Joins (C# Programming Guide)
What is the syntax for an inner join in linq to sql?
Why you don't create View in database, and Select your data from View in LINQ?

LINQ equivalent for SQL

I am trying to convert a ASP.NET project to Entity framework. How to re-write the following query to its LINQ equivalent?
SELECT {Table1 objects}
FROM [Table1] tb1
INNER JOIN [Table2] tb2
ON tb1.Table1ID = tb2.fk_Table1ID
WHERE tb2.fk_attrib1 = '123' AND tb2.fk_attrb2 = '345'
ORDER BY tb1.attrib1
The result is a collection of Table1 objects.
Here Table1 and Table2 correspond to object System.Data.Objects.ObjectSet of ADO.NET Entity Framework.
var results = from tb1 in Context.Table1
join tb2 in Context.Table2 on tb1.Table1ID == tb2.fk_Table1ID
where tb2.fk_attrib1 == "123" && tb2.fk_attrb2 == "345"
orderby tb1.attrib1
select tb1;
Something like this:
context.Table1
.Where( o => o.Table2s.Any( o2 =>
o2.fk_attrib1 == '123' &&
o2.fk_attrib2 == '345' ) )
.OrderBy( o => o.attrib1 )
.ToList();
BTW, LINQPad is great for trying out L2E queries.
This should help you a little bit. I suppose the main problem is with JOIN clause - in EF you can use NavigationProperties and don't need to worry about joining tables - EF will take care of that for you.
Also you are trying to filter on column from joined table. This you can do using Any method to find all Table1 elements that are connected to Table2 where those referenced elements have certain properties/columns. You should also get familiar with All method, as it might be useful to you in future.
from t1 in context.Table1
where t1.Table2s.Any(t2.fk_attrib1 == "123" && t2 => t2.fk_attrb2 == "345")
order by t1.attrib1
select t1;
Edit:
I assume that there is 1:n relationship between Table1 and Table2 which results in enumerable collection as NavigationProperty in Table1 objects.
Edit2:
Fixed error in code - didn't noticed that both attributes are from Table2 not Table1
Should be something like this:
var result = (from tb1 in Table1
from tb2 in Table2
where tb1.Key == tb2.Key &&
tb2.fk_attrib1 = '123' &&
tb2.fk_attrb2 = '345'
select ione).OrderBy(p=>p.attrib1);
Hope this helps.

Apply dynamic where clause to joined table

I need to build a LINQ query that allows me to vary the where clause on a joined table but can't find a way to do it.
A simplified example of the two queries I'm constructing are:
var myQuery = from tab1 in context.Table1
join tab2 in context.Table2 on Table1.ID equals Table2.Table1ID
where tab1.TypeCode == 3
tab2.SomeID == 4 &&
select tab1.ID;
var myQuery2 = from tab1 in context.Table1
join tab2 in context.Table2 on Table1.ID equals Table2.Table1ID
where tab1.TypeCode == 3
tab2.SomeOtherID == 4 &&
select tab1.ID;
The only difference between them being the tab2.SomeID where clause changes to tab2.SomeOtherID.
If the changing where clause was being applied to tab1 I could just add a .Where to the query but how do I use a common query and specify a different tab2 where clause?
Dynamically Composing Expression Predicates
or
(source: scottgu.com)
You need something like this? Use the Linq Dynamic Query Library (download includes examples).
Check out ScottGu's blog for more examples.
You can have optional parameters in queries:
int? someID = null;
int? someOtherID = 4;
var myQuery = from tab1 in context.Table1
join tab2 in context.Table2 on Table1.ID equals Table2.Table1ID
where tab1.TypeCode == 3
&& (someID == null || tab2.SomeID == someID)
&& (someOtherID == null || tab2.SomeOtherID == someOtherID)
select tab1.ID;
Linq-to-SQL will eliminate the parts that can be evaluated client-side from the query, so in the above example the where clause will filter on tab1.TypeCode and tab2.SomeOtherID.

Categories

Resources