How to select a collection nested within another collection in LINQ
Say I have the following:
(--> = 1 to many implemented as a collection in EF code-first)
Message --> UserMessage
Message --> Attachments
When I call the following:
var res = _ctx.DataContext.UserMessage.Where(x => x.UserId)
.Select(m => m.Message).ToList();
EDIT: added classes:
public class Message
{
public int MessageId { get; set; }
public ICollection<Attachment> Attachments { get; set; }
[Required]
public string Text { get; set; }
}
public class Attachment
{
public int AttachmentId { get; set; }
public int MessageId { get; set; }
public virtual Message Message { get; set; }
public string FileServerPath { get; set; }
}
public class UserMessage
{
public int UserMessageId { get; set; }
[Required]
public int MessageId { get; set; }
public Message Message { ge开发者_C百科t; set; }
[Required]
public int UserId { get; set; }
public User User { get; set; }
}
I would expect the res variable to hold all the attachments but it is empty even if there are rows. What am I missing?
Your where condition doesn't make sense, I don't even think it compiles.
You say, you expect res
to hold all attachments. Why should it? You don't even use Attachment anywhere in your query.
Without your actual classes, it is a bit hard to suggest the correct way, but I think it would be something like this:
var res = _ctx.DataContext.UserMessage.Where(x => x.UserId == currentUserId)
.SelectMany(m => m.Message.Attachments)
.ToList();
Now, res
contains all attachments of all messages of the user with the id currentUserId
.
I assumed a class layout like this:
class UserMessage
{
public int UserId {get;set;}
public Message Message {get;set;}
}
class Message
{
public IEnumerable<Attachment> Attachments {get;set;}
// Irrelevant for the query in its current form:
public IEnumerable<UserMessage> UserMessages {get;set;}
}
On the context it needs to be told to acquire the navigation properties with an include such as
_ctx.UserMessage.Include("Attachments")
.SelectMany( ... )
HTH
精彩评论