LINQ equivalent for SQL - c#

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.

Related

Need multiple where conditions to a query with OR operator

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

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?

Select from multiple tables using linq

I am trying to execute the following SQL statement using linq:
SELECT TTT.SomeField
FROM Table1 as T, Table2 as TT, Table3 as TTT
WHERE (T.NumberID = 100 OR T.NumberID = 101)
AND T.QuestionID = 200
AND T.ResponseID = TT.ResponseID
AND TT.AnswerID = TTT.AnswerID
Essentially getting one field from a third table based on primary/foreign key relationships to the other 2 tables. It is expected to have a single result every time.
var query = from t in db.Table1
join tt in db.Table2 on t.ResponseID equals tt.ResponseID
join ttt in db.Table3 on tt.AnswerID equals ttt.AnswerID
where (t.NumberID == 100 || t.NumberID == 101) && t.QuestionID == 200
select ttt.SomeField
If you always expect single result, you can wrap this in ().Single(), or, if there might be no results found, in ().SingleOrDefault().
If I understand you correct. You should read something about Joins I guess.
here

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.

Need help with an Opposite to Inner join Query using LINQ

I have two tables in an XML Dataset. T1, T2. Each of the tables has a ID column.
T1 has a list of Customers
T2 has a list of Orders
I want to build a LINQ query that returns only the ID of the customers that do not have orders. In other words customer ID's that do not exist in the T2 table.
Oh yea, I'm using C#
Thanks!
This requires an outer join and a check on null.
var result = from c in Customers
join d in Details on d.CustomerID equals c.ID into g
where !g.Any()
select c;
I think this will work (please adapt to your DataSets):
var query = from c in T1
where !(from o in T2 select o.CustomerID)
.Contains(c.CustomerID)
select c;
You just need to us a where clause and all:
T1.Where( item1 => T2.All( item2 => item1.ID != item2.ID ) );

Categories

Resources