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

前端之家收集整理的这篇文章主要介绍了c# – 如何从Dapper查询而不是默认(T)返回null?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我通过存储过程使用 Dapper进行一些只读数据库调用.我有一个查询将返回1行或没有.

我正在使用这样的Dapper:

  1. using (var conn = new sqlConnection(ConnectionString))
  2. {
  3. conn.Open();
  4.  
  5. return conn.Query<CaSEOfficer>("API.GetCaSEOfficer",new { Reference = reference },commandType: CommandType.StoredProcedure).FirstOrDefault();
  6. }

返回的CaSEOfficer对象如下所示:

  1. public class CaSEOfficer
  2. {
  3. public string Title { get; set; }
  4. public string FirstName { get; set; }
  5. public string LastName { get; set; }
  6. public string Email { get; set; }
  7. public string Telephone { get; set; }
  8. }

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

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

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

但当它返回什么我得到:

  1. {
  2. title: null,firstName: null,lastName: null,email: null,telephone: null
  3. }

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

解决方法

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

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

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

猜你在找的C#相关文章