Question

I have this Parent -> Child -> Child relationsship. (Store -> Message -> MessageText).

In the projected result, I want to have all related Messages from the Store, but only a filtered sub set of the MessageTexts (for a specific language). So I was playing with something like:

  var result = from s in context.Stores 
  join m in context.Messages on s.Id equals m.MessageId
  join mt in context.MessageTexts on m.MessageId equals mt.MessageId  into mts
  from filtered in mts.Where (mt => mt.LanguageId == 1)

  select new
    {
      StoreName = s.Name,
      Messages = s.Messages,
    };

So the filtered set is what I want to appear in the result.Messages.MessageTexts navigation property.
How can I do that in one query?

Was it helpful?

Solution

I assume you have navigation properties available. That would make

from s in context.Stores
select new {
               StoreName = s.Name,
               Messages = from m in s.Messages
                          from mt in m.MessageTexts
                          where mt.LanguageId == 1
                          select mt
           }

OTHER TIPS

You can do it with multiple queries:

var stores = context.Stores.Include("Messages").ToList();
var messageIds = stores.Messages.Select(m => m.MessageId).ToList();
var messageTexts = context.Messagetexts.Where(m => messageIds.Contains(m.MessageId) && m.LanguageId == 1);

With one query and just one level deep hierarchy you can do it like this:

var query = from s in context.Stores
             Select Stores = s
                    Messages = from m in context.Messages.Where(m => m.MessageId.Equals(s.Id) && someOtherFilter)

var result = from s in query.Stores.ToList();

so i suspect you can filter deeper nested childs like this:

var query = from s in context.Stores
            Select Stores = s
                   Messages = from m1 in context.Messages
                              Select Messages = m1
                                     MessageTexts = from context.MessageTexts.Where(m => m.MessageId.Equals(m1.MessageId) && m.LanguageId == 1);

var result = from s in query.Stores.ToList();

I have no VS here, will test it in some hours.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top