tags:

views:

97

answers:

3
+1  Q: 

linq not in query

I'm lost in linq-land, trying to turn this SQL (which give the results I need) into something that works in linq / C#. The result will end up in a SelectList.

select Agencies.AgencyName, Agencies.AgencyId
from Agencies
where Agencies.Active = 1 and Agencies.AgencyId not in (
  select distinct Agencies.AgencyId
  from Agencies, AgenciesDonors
  where AgenciesDonors.AgencyId = Agencies.AgencyId and
        AgenciesDonors.DonorId = '73B29E01-8BF0-4EC9-80CA-089BA341E93D')

The Guid value will be passed in each time.

Help very much appreciated after a long day of getting nowhere.

EDIT: I should have said I'm working in an MVC 1.0 / EF context. Not sure how that changes the initial answers.

+1  A: 

This should do the trick

var query = from c in dc.Agencies 
            where c.agencies == 1 && 
                  !(from o in dc.AgenciesDonors 
                    where o.DonorId = myDonorId 
            select o.AgencyId).Contains(c.AgencyId) 
            select c;

Linq to SQL will turn the not contains into a not exists which usually has better performance than a not in SQL statement.

Dave Barker
+1  A: 

Unless I'm missing something, bringing in the Agencies table into the subquery is unnecessary. So something like this should work:

from a in dataContext.Agencies
where a.Active == 1 &&
      !(from inner in dataContext.AgenciesDonors
        where inner.DonorId == donorID
        select inner.AgencyId).Contains(a.AgencyId)
select a
Rex M
A: 
var query = from a in dc.Agencies 
            let ad = from o in dc.AgenciesDonors 
                     where o.DonorId = myDonorId 
                     select o.Agencies.AgencyId
            where a.Active == 1 && !ad.Contains(a.AgencyId) 
            select c;

I find this to be a neater syntax, since it negates the need to nest a join statement on AgenciesDonors to Agencies to get the AgencyId, this must execute on a DataContext (dc), since o.Agencies.AgencyId in the "let" statement will only work when run as IQueryable

Neil
Sorry for being dense, but what do I need to do to get a dc with I'm in an MVC / EF setting and I already have a db using EntitySets?
Dale
basically your dc should be created when you add your edmx (for EF), so your datacontext is the class that you use when making calls to the database through EF
Neil