没有外键的实体框架连接

发布于 2024-10-04 17:20:56 字数 462 浏览 1 评论 0 原文

我有一个消息表,其中每行都有发送该消息的用户的 ID。 但我无法编辑数据库,并且没有外键。 没有任何关系可以加入吗?

var msgs = (from m in dbContext.messages
           join a in dbContext.users on m.userid equals a.id into sender
           where (m.date > LastReceivedDate)
           orderby m.date
           select new
           {
                Sender = sender.FirstOrDefault(),
                Message = m
           })

这就是我的代码,它可以运行,但不会返回任何内容。当我取消连接时,我得到了结果。

谢谢

I have a messages table which has an id of the user that sent it in each row.
But I cannot edit the database, and there are no foreign keys.
Is it possible to join without any relationships?

var msgs = (from m in dbContext.messages
           join a in dbContext.users on m.userid equals a.id into sender
           where (m.date > LastReceivedDate)
           orderby m.date
           select new
           {
                Sender = sender.FirstOrDefault(),
                Message = m
           })

Thats my code, and it runs, but never returns anything. When I take the join away I get results.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

熊抱啵儿 2024-10-11 17:20:56

除了我对 Craig Stuntz答案,如果您放弃 ,您可以消除第二个查询,并在单个查询中将其全部返回。 FirstOrDefault() 并且可以在连接没有出现用户时处理 Sender 可能为 null 的情况。

var msgs = (from m in dbContext.messages

                        join a in dbContext.users on m.userid equals a.id into sender
                        where (m.date > LastReceivedDate)
                        orderby m.date

                        select new
                        {
                            Sender = sender,
                            Message = m
                        })

In addition to my comment on Craig Stuntz's answer, you can get the 2nd query eliminated and have it all returned in a single query if you forgo the .FirstOrDefault() and can deal with Sender possibly being null if the join turns up no users.

var msgs = (from m in dbContext.messages

                        join a in dbContext.users on m.userid equals a.id into sender
                        where (m.date > LastReceivedDate)
                        orderby m.date

                        select new
                        {
                            Sender = sender,
                            Message = m
                        })
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文