How to return null from a Dapper request and not the default (T)?

I use Dapper for some read-only database calls through a stored procedure. I have a query that will either return 1 row or nothing.

I am using Dapper as follows:

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

The returned CaseOfficer object is as follows:

 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; } } 

This then returns through the ASP.NET Web API application as JSON.

When the stored procedure returns the result, I get the following:

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

But when it returns nothing, I get:

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

How can I make Dapper return null (so that I can check and respond with 404), and not by default (CaseOfficer)?

+6
source share
2 answers

If your SP does not return a string, then dapper will not return a string; so the first thing to check is: did your SP possibly return an empty string? A string of all null ? Or did he return 0 rows?

Now, if no row has been returned, FirstOrDefault (the standard LINQ-to-Objects thing) will return null if CaseOfficer is a class or the default instance if CaseOfficer is a struct . So, the following: check CaseOfficer is a class (I cannot come up with a reasonable reason that would be struct ).

But: a dapper with FirstOrDefault will usually do what you want.

+7
source

You can set the default properties.

For instance:

 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; } } 

Now CaseOfficer got auto properties

+1
source

Source: https://habr.com/ru/post/893887/


All Articles