Reputation: 6185
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?
Upvotes: 1
Views: 4261
Reputation: 44307
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;
Upvotes: 1
Reputation: 204129
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;
Upvotes: 1