tags:

views:

472

answers:

2

Hi Geeks,

I met a issue with LTS My code as below:

return from p in _db.Companies
where p.Deleted == false &&
(from q in _db.Contacts_Companies
where q.ContactId == contactId && q.Deleted == false
select q.CompanyId).Equals(p.Id)
select p;

I know the issue comes from the CompanyId.Equals(Id) they are both Int32, but I am a bit confused that Int32 cannot be compared? If I use Contains, it wont match my requirement.

How could I overcome this issue?

+1  A: 

Your "inner" query is selecting a list of company IDs (even if that list only contains one item), so it's not correct to compare it to a single value.

Try selecting only the first item:

return from p in _db.Companies 
       where !p.Deleted && (
           from q in _db.Contacts_Companies 
           where q.ContactId == contactId && !q.Deleted 
           select q.CompanyId).FirstOrDefault() == p.Id
       select p;
Matt Hamilton
+1  A: 

The problem originates with your sub-query:

from q in _db.Contacts_Companies
where q.ContactId == contactId && q.Deleted == false
select q.CompanyId

This doesn't return an int - it returns (as shown in your error message) IQueryable<int>.

Perhaps you're caught up on the deferred execution semantics of linq?

Anyway, to solve this you need to convert from the IQueryable<int> to a simple int. Since you're always expecting exactly one result, I'd suggest adding .First():

return from p in _db.Companies
where p.Deleted == false &&
(from q in _db.Contacts_Companies
where q.ContactId == contactId && q.Deleted == false
select q.CompanyId).First().Equals(p.Id)
select p;
Bevan
Yeah, you are right.BTW, can I write in anther way make the query perform better in this kind of situation?
ldsenow
Oh right, there is a bit more to goI've modified itreturn from p in _db.Companies where p.Deleted == false
ldsenow
I'm not sure about how to rewrite this for better performance - my experience is more in the Linq for Objects realm than Linq to SQL. Are you sure you want to use FirstOrDefault() in your code? This will silently hide the case where there's no match.
Bevan