linq to sql join

  • Thread starter Thread starter Chris
  • Start date Start date
C

Chris

hi,
I have i.e a linq result:
var result = from c in context.c select c;

I want to write a second linq query joined with the result above:
var second = from d in context.d join ... <now, I want to join it with
result>.

is it possible?
 
Chris said:
hi,
I have i.e a linq result:
var result = from c in context.c select c;

I want to write a second linq query joined with the result above:
var second = from d in context.d join ... <now, I want to join it with
result>.

is it possible?

Why do you want it in two separate queries? You could perform the join
directly when you write the first of the queries:

var result = from c in context.c
join d in context.d on c.field equals d.field
select new { c.something, d.something };

This will send the join to the database server where it will be resolved
efficiently. If you retrieve a resultset and then perform the join in a
second linq query, then the join will have to be performed in memory at the
client side, which will normally require transferring unnecesary records
from the server into the client.
 
ok, thank u very much for help.
Anyway, I have sql query:

select * from tab n
join
(
select a, b, c from tab
where a in (select x from tab2 where y=z)
)m
on n.a=m.a

I want to have this query in linq to sql. Can u help me? I have problems how
to write where in (<select>) clause and then join it.
 
Chris said:
Anyway, I have sql query:

select * from tab n
join
(
select a, b, c from tab
where a in (select x from tab2 where y=z)
)m
on n.a=m.a

I want to have this query in linq to sql. Can u help me? I have problems
how
to write where in (<select>) clause and then join it.

You dont't have subqueries in linq, so you will need to rewrite your code
as a join. If I am not mistaken, your query can be rewritten in some way
similar to the following (and if I am mistaken, just ask the question in one
of the Sql forums and someone will tell you how to refactor your query so
that the subclause is converted into a join):

select tab1.*, tab2.a, tab2.b, tab2.c from tab1
join tab2 on tab1.a=tab2.a
join tab3 on tab2.a=tab3.x
where tab3.y=z

Once your query is refactored in this way, you can easily express it in
LINQ:

var q = from v1 in cts.tab1
join v2 in ctx.tab2 on v1.a equals v2.a
join v3 in ctx.tab3 on v2.a equals v3.x
where v3.y==z
select new {v1, v2.a, v2.b, v2.c };
 
Ok, thank u.
One question abou linq query. I wrote:
join v2 in ctx.tab2 on v1.a equals v2.a

can u write:
join v2 in ctx.tab2 on v1.a = v2.a

(= instead of equals)?
 
Chris said:
Ok, thank u.
One question abou linq query. I wrote:
join v2 in ctx.tab2 on v1.a equals v2.a

can u write:
join v2 in ctx.tab2 on v1.a = v2.a

(= instead of equals)?

No, the "join" in LINQ requires the "equals" keyword. You use == in the
"where" clause (note the C-style "double equals" instead of the SQL-style
"single equals", since we are writng C# and not SQL).
 
Back
Top