Linq的奇怪行为

时间:2011-11-11 10:52:35

标签: linq entity-framework-4 sql-server-ce

我有一个运行带有Sql Server CE 3.5数据库的Windows窗体应用程序(.NET 4.0),我通过EF连接访问该数据库。

这是我的初始查询,它返回两个结果:

var list = db.UserPresentation
                         .Select(up => new
                         {
                             UserPresentationID = up.UserPresentationID,
                             PresentationName = up.PresentationName,
                             DateRequested = up.DateRequested,
                             Edit = string.Empty,
                             Delete = string.Empty,
                             Download = string.Empty
                         })
                         .OrderByDescending(up => up.DateRequested)
                         .ToList();

现在我引入一个外部变量和一个where子句,它返回零结果。如果我在LinqPad中运行相同的代码,它将返回2个结果。

 int userID = 2;

            // load list of user presentations
            var list = db.UserPresentation
                         .Where(up => up.UserID == userID)
                         .Select(up => new
                         {
                             UserPresentationID = up.UserPresentationID,
                             PresentationName = up.PresentationName,
                             DateRequested = up.DateRequested,
                             Edit = string.Empty,
                             Delete = string.Empty,
                             Download = string.Empty
                         })
                         .OrderByDescending(up => up.DateRequested)
                         .ToList();

现在我在查询中对userid进行硬编码,然后再次返回两个结果:

var list = db.UserPresentation
                         .Where(up => up.UserID == 2)
                         .Select(up => new
                         {
                             UserPresentationID = up.UserPresentationID,
                             PresentationName = up.PresentationName,
                             DateRequested = up.DateRequested,
                             Edit = string.Empty,
                             Delete = string.Empty,
                             Download = string.Empty
                         })
                         .OrderByDescending(up => up.DateRequested)
                         .ToList();

我真的很难过。知道这里发生了什么吗?

2 个答案:

答案 0 :(得分:0)

UserID可以为空吗?

如果是这样,请确保.Where(up => up.UserID.HasValue && up.UserID.Value == userID)

我曾经有过类似于可以为空的日期时间

答案 1 :(得分:-1)

您是否尝试在变量中分配相同的硬编码值?我的猜测是你的数据中没有找到变量中的值,也就是说你确定变量名是正确的。