Figure out how you would do this in standard SQL and then pick up a copy of Linqer (http://www.sqltolinq.com/). This product will convert almost any SQL statement into a LINQ query. It's not free, but not expensive either, and comes with a 30 day trial period. I have found it to be extremely useful.
+1
A:
Randy Minder
2010-05-10 20:05:25
A:
Sounds like you are trying to do a WHERE NOT IN, like maybe:
'var companiesWithoutSubcontracts =
from noSub in Companies
where !(from withSub in Companies
select withSub.company_id)
.Contains(noSub.company_id)
select noSub;
`
Jonathan Bates
2010-05-10 20:29:29
A:
I have not tested it and it may well be that LINQ to SQL fails to translate the query, but in theory this should work.
var result = context
.Subcontracts
.Select(subcontract => new
{
Subcontract = subcontract,
NotAssignedCompanies = context
.Companies
.Where(company => !company.Subcontracts.Contains(subcontract))
});
This will return all not assigned companies for all subcontracts. If you only need the information for one specific subcontract, the following query will be sufficient.
var notAssignedCompanies = context
.Companies
.Where(company => !company.Subcontracts.Contains(specificSubcontract));
Daniel Brückner
2010-05-10 20:35:17
+1
A:
This should work:
var noContracts =
from c in db.Companies
join sc in db.Subcontracts.Where(sc => sc.active_status == 1) on c.company_id equals sc.company_id into compGroup
from cg in compGroup.DefaultIfEmpty()
where cg.company_id == null
select c;
This does a LEFT OUTER JOIN
. All subcontracts without a corresponding company_id will be assigned a NULL
value for company_id, which it then selects.
Nick
2010-05-10 20:44:01
Thanks. I can get it where it's selecting companies with active_status == 1 that are not in subcontracts.company_id. But, I can't seem to get it to work where it only matches subcontracts with active_status == 1. Where do I put the where in the join?
RememberME
2010-05-10 21:20:53
@RememberME Edited to do what I think you want. This will also return companies with subcontracts that are inactive
Nick
2010-05-10 21:36:40
You don't really need the join. LINQ to SQL is perfectly capable of handling a sub-select in the where clause.
Jacob Proffitt
2010-05-10 22:00:34
@Jacob Proffitt At worst a join performs equally to a subquery, at best it is much more efficient than a subquery, especially when EXISTS is involved.
Nick
2010-05-11 03:08:08
Oh yeah. I'm not judging the join *bad*. It's just not required.
Jacob Proffitt
2010-05-11 05:22:17
+1
A:
The sub-select is pretty much the same in LINQ.
var noSubs = from company in context.Companies
where company.active_status == 1 &&
!(from subcontract in context.Subcontracts
where subcontract.active_status == 1
select subcontract.company_id).Contains(company.company_id)
select company;
Linq to SQL will translate this as a "not exists" on the subcontract table.
Jacob Proffitt
2010-05-10 21:59:24