如何在 LINQ 中选择嵌套在另一个集合中的集合
假设我有以下内容:
(--> = 1 to many Implemented as a collection in EF code-first)
Message --> UserMessage
留言 -->附件
当我调用以下内容时:
var res = _ctx.DataContext.UserMessage.Where(x => x.UserId)
.Select(m => m.Message).ToList();
编辑:添加的类:
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 { get; set; }
[Required]
public int UserId { get; set; }
public User User { get; set; }
}
我希望 res 变量保存所有附件,但即使有行,它也是空的。我缺少什么?
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 { get; 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的 where 条件没有意义,我什至认为它无法编译。
您说,您希望
res
保存所有附件。为什么应该这样?您甚至不在查询中的任何地方使用附件。如果没有您的实际类,很难建议正确的方法,但我认为它会是这样的:
现在,
res
包含 id用户的所有消息的所有附件>当前用户ID
。我假设了这样的类布局:
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:
Now,
res
contains all attachments of all messages of the user with the idcurrentUserId
.I assumed a class layout like this:
之类的包含来获取导航属性
在上下文中,需要告诉它使用HTH
On the context it needs to be told to acquire the navigation properties with an include such as
HTH