c# - 具有可为空 Guid 的 PetaPoco ExecuteScalar

标签 c# asp.net-mvc petapoco

我绞尽脑汁想弄清楚为什么 petapoco 的“Exists()”在应该返回 true 的地方返回 false。我用这样的东西来测试:

一个简单的 petapoco 模型:

[TableName("WorkLog")]
[PrimaryKey("Id")]
public class WorkLog : DefaultConnectionDB.Record<WorkLog>
{
     public int Id { get; set; }
     public Guid? Customer { get; set; }
     public Guid? Project { get; set; }
}

具有与上述相同结构的数据库表,填充有 Id 和客户(只有项目为空)。

创建一个测试对象:

var x = new WorkLog {Id = 0, Customer = 'xxx-xxx-xxx...', Project = null}

根据“项目”查询数据库中是否存在工作日志:

var exist = db.Exists<WorkLog>("Project=@p", new { p = x.Project });

在这种情况下,结果为“false”。如果我使用项目的 Guid 填充模型、数据库和查询,它会像它应该的那样返回“true”。

所以我猜测这与null和DbNull比较有关,但我似乎无法找到合适的地方进行挖掘。我已经尝试使用辅助方法在查询前将“null”转换为“DbNull”,但它仍然返回 false。

临时解决方案:

目前我已经通过...解决了这个问题

var exist = db.Exists<WorkLog>(x.Project == null ? "Project IS NULL" : "Project=@p", new { p = x.Project });

这现在按预期工作,但我希望该方法可以正常调用并仍返回预期结果。

最佳答案

与 PetaPoco 相比,ADO.net 方面的问题更多。 PetaPoco 仅创建参数并用您的值填充它们。

但是,处理 WHERE 子句中的 null 是棘手的,因为 this MSDN article说:

Testing for Null

If a column in a table (in your database) allows nulls, you cannot test for a parameter value of "equal to" null. Instead, you need to write a WHERE clause to test whether both the column is null and the parameter is null. The following SQL statement returns rows where the LastName column equals the value assigned to the @LastName parameter, or whether both the LastName column and the @LastName parameter are null.

SELECT * FROM Customers
WHERE ((LastName = @LastName) OR (LastName IS NULL AND @LastName IS NULL))

关于c# - 具有可为空 Guid 的 PetaPoco ExecuteScalar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20513241/

相关文章:

c# - 如果重写的方法返回不同的值,是否违反了里氏原则?

c# - 表格之间的连接

c# - 自动增量不适用于模型

java - Java Micro ORM等效项

vb.net - 传递匿名类型 VB.NET

c# - 如何在 Rhino Mocks 3.6 中将 Expect 设置为扩展方法

c# - Entity Framework 中数据库条目的版本历史

asp.net-mvc - 同一 Controller 的多个 MVC Controller 实例

c# - 无法打开登录请求的数据库 "Database"

petapoco - 如何使用 PetaPoco 显式包含映射表