Option 1 - using Contains:
var res = from m in db.messages
where m.id == message_id
from p in db.persons
where m.recipients.Split(",").Select(i => Int32.Parse(i))
.Contains(p.id)
select new Message() {
msg = m,
person = p
};
The idea:
- Get the messages as in your original query
- Get all persons where contained in the recipient list
- Continue with your original query
Option 2 - using a LINQ join (maybe more complicated than it needs to be):
var res = from m in db.messages
where m.id == message_id
from r in m.recipients.Split(",")
select new {
Message = m,
Recipient = Int32.Parse(r)
} into rec
join p in db.persons on rec equals p.id
select new Message () {
msg = m,
person = p
};
The idea:
- Get the messages as in your original query
- Split the string into a list of Int32
- Join this list against
db.persons
- Continue with your original query
Not sure which of these is faster, you'll have to check.
I would also shy away from using comma-delimited strings as a foreign key reference namely because of the troubles you're having here. They're ugly to look at and a true pain to manipulate. Instead, if you have control over the schema, consider a one-to-many relation table having MessageId
and PersonId
. Of course if you don't have control, you're stuck.
Disclaimer: These are untested, so may need some tweaking for the code to work. The algorithms however should be ok.