RIA Services, where clause using child attributes
I have a MessageThread entity which contains Message entities. The foreign key is set up so I can navigate from MessageThread to all the messages easily. Each message has a from and to address. I want to write a query to retrieve all message threads for which a particular address has either written or received a message.
MessageThread
{
EntityCollection<Message> messages;
}
Message
{
long FromAccount;
long ToAccount;
}
The query should be something like this, but I can't figure out how to navigate to the To and From addresses all the way from the MessageThread
class.开发者_开发技巧
public IQueryable<MessageThread> GetMessageThreads(long userAccount)
{
return from messageThread in this.ObjectContext.MessageThreads
where messageThread.Messages.ToAddress == userAccount ||
messageThread.Messages.FromAddress == userAccount
select messageThread;
}
That query won't work because messageThread.Messages is a collection and both ToAddress
and FromAddress
are not directly accessible from the collection.
Select the child items first and then include the parent. Then at the end, just select a list of the parent entity that you were after.
Messages.Include("MessageThread")
.Where(m => m.FromAccount == userAccount
|| m.ToAccount == userAccount)
.Select(m => m.MessageThread)
If you leave the select off the end you get a list of messages with the parents included. It depends on what you where after.
OR.... (this, which is a bit neater)
MessageThreads.Where(s => s.Messages.Any( m => m.FromAccount == userAccount
|| m.ToAccount == userAccount))
精彩评论