从 lambda 查询结果访问关联时出现问题
当您的子记录通过 lambda 查询加载时,是否有人在使用 LINQ to SQL 加载关联时遇到问题?例如:
var orderLine = db.OrderLines.
Where(ol => ol.ID == orderLineID select ol).
First();
// navigate to order via the association
var order = orderLine.GetOrder();
我得到的基本上是 GetOrder() 的空结果。
但如果我这样做:
var orderLine = (from ol in db.OrderLines where ol.ID == orderLineID).First();
var order = orderLine.GetOrder();
效果很好。
什么会导致这种情况?这是一个错误吗?
编辑:这是与 Lambda 表达式一起使用的实际代码,注释掉了它不起作用
var msg = db.Messages.Where(m => m.ID == msgID).First(); if (msg.SentTS.HasValue) return; // Get the message recipients // I don't get it.. why doesn't lambda expressions work here? returns 0 results! // var testtos = msg.GetMessageTos.Where(mt => mt.Active); var tos = from mt in db.MessagesTos where mt.Active && mt.MessageID == msgID select mt;
Has anyone had problems gettting associations to load using LINQ to SQL when your child record was loaded via a lambda query? For example:
var orderLine = db.OrderLines.
Where(ol => ol.ID == orderLineID select ol).
First();
// navigate to order via the association
var order = orderLine.GetOrder();
What I get basically is a null result from GetOrder().
But if I do this instead:
var orderLine = (from ol in db.OrderLines where ol.ID == orderLineID).First();
var order = orderLine.GetOrder();
Works fine.
What can cause this? Is this a bug?
EDIT: Here's the actual code that WORKS with the Lambda expression commented out that DOESN'T WORK
var msg = db.Messages.Where(m => m.ID == msgID).First(); if (msg.SentTS.HasValue) return; // Get the message recipients // I don't get it.. why doesn't lambda expressions work here? returns 0 results! // var testtos = msg.GetMessageTos.Where(mt => mt.Active); var tos = from mt in db.MessagesTos where mt.Active && mt.MessageID == msgID select mt;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你也可以试试这个,我觉得这样更干净一点。
我相信在您的非工作示例中您想使用
.First()
而不是.Single()
。You can also try this, I think it's a little cleaner.
I beileive in your non-working example you want to use
.First()
instead of.Single()
.在我看来,问题更多地与关联有关,而不是与 lambda 表达式有关。
在您的场景中,这应该有效:
虽然这不会:
至于为什么它不起作用,我建议查看设计器中的关联并检查其是否正确匹配数据库模型(匹配正确的列)。我还建议确认 msg.SentTS 实际上是空的,无论您对其运行任何进一步的查询。
It seems to me that the problem has more to do with the association than lambda expressions.
In your scenario, this should work:
while this won't:
As to why it doesn't work, I suggest taking a look at the association in the designer and checking its matching the db model correctly (matching the correct columns). I also suggest to confirm that msg.SentTS is effectively coming empty, regardless of any further query you run on it.
请参阅我的编辑以获取有效的代码。我想有时“答案”是做有效的事情,而不一定是你理解的事情。
See my EDIT for the code that works. I guess sometimes the "Answer" is to do what works, not necessarily what you understand.