0

I'm trying to create a linq join statement which joins an object from a table based on two conditions

MESSAGES
======
ID (int)
UserID (Guid)

MESSAGEPART
======
MessageID (int) 
IsPlaintext (bool)
MessageContent (nvarchar(max))

Here's the query I want to write, essentially:

var messages = from m in db.Message 
               join p in db.MessagePart on m.ID equals p.MessageID 
                                        and p.IsPlaintext equals false

Unfortunately, this doesn't work. This is the best I can do.

var messages = from m in db.Message 
               join p in
               (from x in db.MessagePart where x.IsPlaintext == false select x) 
               on m.ID equals p.MessageID

This seems a bit longwinded. Is there a more elegant way of achieving it?

roryok
  • 9,325
  • 17
  • 71
  • 138

2 Answers2

4

An elegant solution.

  var messages = from m in db.Message 
                   join p in db.MessagePart on m.ID equals p.MessageID 
                   where p.IsPlaintext == false
Ishtiaq
  • 980
  • 2
  • 6
  • 21
0

You could try this one:

var messages = from m in db.Message 
               join p in db.MessagePart 
               on new { m.ID, false } equals { p.MessageID, p.IsPlaintext }

or you could try this one:

var messages = db.Message.Join(db.MessagePart.Where(x=>x.IsPlainText==false),
                               x=>x.ID,
                               y=>y.Id,
                               (x,y)=>new {});

Inside the new { } you will declare the properties of the anonymous type you select.

ps. If you update your post and show there which fields you want to select, I could update also mine.

Christos
  • 53,228
  • 8
  • 76
  • 108
  • I like like your first answer because it solves a problem I was having the other day, but I think the SQL it would generate would be nasty as.. – Michael Coxon Jun 13 '14 at 12:24