如何从Dapper查询而不是默认(T)返回null?

我正在使用Dapper通过存储过程进行一些只读数据库调用。 我有一个查询将返回1行或没有。

我正在使用这样的Dapper:

using (var conn = new SqlConnection(ConnectionString)) { conn.Open(); return conn.Query("API.GetCaseOfficer", new { Reference = reference }, commandType: CommandType.StoredProcedure).FirstOrDefault(); } 

返回的CaseOfficer对象如下所示:

 public class CaseOfficer { public string Title { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Telephone { get; set; } } 

然后通过ASP.NET Web API应用程序将其作为JSON返回。

当存储过程返回结果时,我得到以下内容:

 { title: "Mr", firstName: "Case", lastName: "Officer", email: "test@example.com", telephone: "01234 567890" } 

但当它返回任何我得到的:

 { title: null, firstName: null, lastName: null, email: null, telephone: null } 

我怎样才能让Dapper返回null(所以我可以检查并回复404),而不是默认(CaseOfficer)?

如果你的SP没有返回一行,那么dapper将不会返回一行; 首先要检查一下:您的SP是否可能返回空行? 一行所有null s? 或者它返回0行?

现在,假设没有返回任何行,如果CaseOfficer是一个class ,则FirstOrDefault (标准的LINQ-to-Objects事物)将返回null ,如果CaseOfficer是一个struct ,则返回默认实例。 接下来:检查CaseOfficer是一个class (我想不出任何理智的struct )。

但是:使用FirstOrDefault通常已经做到了你想要的。

您可以设置默认属性。

例如:

 public class BaseEntity { public BaseEntity() { if (GetType().IsSubclassOf(typeof(BaseEntity))) { var properties = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties) { // Get only string properties if (property.PropertyType != typeof (string)) { continue; } if (!property.CanWrite || !property.CanRead) { continue; } if (property.GetGetMethod(false) == null) { continue; } if (property.GetSetMethod(false) == null) { continue; } if (string.IsNullOrEmpty((string) property.GetValue(this, null))) { property.SetValue(this, string.Empty, null); } } } } } public class CaseOfficer : BaseEntity { public string Title { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Telephone { get; set; } } 

现在,CaseOfficer获得了自动属性