How to write this T-SQL in LINQ to sQL?

select * from table1 where pkey1 in
(select pkey2 from table2 where column1='abc')

Where pkey1 and pkey2 are both int columns.

+3
source share
5 answers

sort of:

from t1 in table1
let x = from t2 in table2 where t2.column1.Equals("abc") select t2
where t1.pkey1.Equals(x.pkey2)
select t1;

and you eventually know what helps you let:)

+4
source

Not a LINQ answer, but a perfectly valid LINQ-to-SQL one:

var results = ctx.ExecuteQuery<Table1>(@"
    select * from table1 where pkey1 in
    (select pkey2 from table2 where column1='abc')").ToList();

You do not need to transfer control over each request to LINQ; indeed, in many cases, a well-written TSQL user query can be much more efficient than one generated from LINQ-to-SQL. Which is not criticism of LINQ-to-SQL (it does an excellent job with most simple queries, etc.).

+2
source
var query = from a in db.table1
            join b in db.table2 on a.pkey1 equals b.pkey2
            where b.column1 == "abc"
            select a;
+2
from t in table1
join u in table2 on t.pkey1 equals u.pkey2
where u.column1 == "abc"
select t;
+2

:

var q = from t2 in table2.Where(x => x.column1 == "abc")
        from t in table1.Where(x => x.pkey1 == t2.pkey2)
        select t;

Distinct() , . SQL :

SELECT [t1].*
FROM table2 AS [t2], table1 AS [t1]
WHERE ([t2].[column1] = 'abc') AND ([t1].[pkey1] = [t2].[pkey2])
0

Source: https://habr.com/ru/post/1781812/


All Articles