linq query help

N

Nick

Hello,

I need some assistance with a LINQ query. I've got a simple query:

var q = from t in db.Table1 select t;

Based on user input I'm adding some where clauses:

if (condition1)
q = q.Where(t => t.Field1==1);
if (condition2)
q = q.Where(t => t.Field2==2);

Table1 has a sub table. Based on a condition I want find the Table1 records
that have one or more Table2 records. If I were using sql I would do
something like this:

select * from Table1 t1 where exists (select * from Table2 t2 where
t1.id=t2.id and t2.field1='somevalue')

How can I do this in LINQ given that I have added the above where clauses
based on those conditions?

Thanks,
Nick
 
F

Frans Bouma [C# MVP]

Nick said:
Hello,

I need some assistance with a LINQ query. I've got a simple query:

var q = from t in db.Table1 select t;

Based on user input I'm adding some where clauses:

if (condition1)
q = q.Where(t => t.Field1==1);
if (condition2)
q = q.Where(t => t.Field2==2);

Table1 has a sub table. Based on a condition I want find the Table1 records
that have one or more Table2 records. If I were using sql I would do
something like this:

select * from Table1 t1 where exists (select * from Table2 t2 where
t1.id=t2.id and t2.field1='somevalue')

How can I do this in LINQ given that I have added the above where clauses
based on those conditions?

Use the Queryable.Any extension method:
q=q.Where(t=>t.Table2s.Any(t2=>t2.Field1==someValue));

FB
--
------------------------------------------------------------------------
Lead developer of LLBLGen Pro, the productive O/R mapper for .NET
LLBLGen Pro website: http://www.llblgen.com
My .NET blog: http://weblogs.asp.net/fbouma
Microsoft MVP (C#)
------------------------------------------------------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top