简单 LINQ To 实体查询的问题

发布于 2024-09-19 19:08:49 字数 354 浏览 16 评论 0原文

我有一个非常简单的 LINQ To Entities 查询,如下所示:

   var orderID = 1;
    var orders = (from o in db.Orders
                where o.OrderID == orderID
                select o).SingleOrDefault();

谁能告诉我为什么这个查询不起作用?它甚至不抛出异常。我还检查了 SQL 分析器,上面的查询甚至没有触发相应的 SQL 查询。但是,当我直接将 orderID 的值插入查询 where o.OrderID == 1 时,一切正常。

I have a very simple LINQ To Entities query as follows:

   var orderID = 1;
    var orders = (from o in db.Orders
                where o.OrderID == orderID
                select o).SingleOrDefault();

Can anyone tell me why this query wouldn't work? It doesn't even not throw an exception. I have also checked the SQL profiler and the above query does not even fire the corresponding SQL query. But when I directly plugin the value of the orderID into the query where o.OrderID == 1 then everything works fine.

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

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

发布评论

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

评论(1

深海夜未眠 2024-09-26 19:08:50

首先,一个更简单的查询是

var specifiedOrders = db.Orders.SingleOrDefault(o => o.OrderID == orderID);

其次,你确定你的查询没有在sql中触发吗?默认情况下,Linq 将尽可能推迟查询执行。这意味着只有当您调用 GetEnumerator 或对查询执行类似操作时,它才会执行查询。但是,在您的示例中, .SingleOrDefault() 调用应该执行查询。

检查以下内容:

  1. 查询的结果。订单的价值是多少?
  2. 如果您在 Visual Studio 中执行此操作,请将鼠标悬停在 db.Orders 上并检查其值。
  3. 您是否连接到正确的数据库?

Firstly, a much simpler query would be

var specifiedOrders = db.Orders.SingleOrDefault(o => o.OrderID == orderID);

Secondly, are you sure you query is not firing in sql? By default Linq will defer the query execution as late as possible. This means it will only execute a query when you call GetEnumerator or a similar operation on the query. However in your example the .SingleOrDefault() call should execute the query.

Check the following:

  1. The result of the query. What is the value of orders?
  2. If you execute this in Visual Studio, hover over db.Orders and check its value.
  3. Are you connecting to the correct database?
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文