1

I have a basic selection task to be carried out

var query = db.Candidate.Where(.....

but I want the where to be on another table called Tag

in sql it would be

select * from Candidate
join Tag on Tag.candidateId = Candidate.tagId and Tag.tagId = 7

Thus getting all Candidates with tag 7

Im trying to do this directly with a Where, is this possible or do I need to use Linq to SQL.

leppie
  • 115,091
  • 17
  • 196
  • 297
Dale Fraser
  • 4,623
  • 7
  • 39
  • 76

3 Answers3

2

You can use a Join in LINQ to do that:

var candidates = from candidate in db.Candidates
                 join on tag in db.Tags
                 where candidate.CandidateId == tag.TagId
                 select candidate
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
2

Try doing it with .Join as shown below :-

var query = db.Candidate.Join(db.Tags, r => r.tagId , p => p.tagId , (r,p) => new{r.Name});
Neel
  • 11,625
  • 3
  • 43
  • 61
1

You didn't show the relations, but it must be possible to do something like:

var query = db.Candidate
              .Include(c => c.Tags)
              .Where(c => c.Tags.Any(t => t.ID == 7))

Just query the candidates where a candidate has any tag that has the ID you're looking for. This will be written out more or less as the SQL you show.

You can omit the Include() if you have lazy loading enabled.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272