c# – 如何从Dapper查询而不是默认(T)返回null?
发布时间:2020-12-15 08:22:11 所属栏目:百科 来源:网络整理
导读:我通过存储过程使用 Dapper进行一些只读数据库调用.我有一个查询将返回1行或没有. 我正在使用这样的Dapper: using (var conn = new SqlConnection(ConnectionString)){ conn.Open(); return conn.QueryCaSEOfficer("API.GetCaSEOfficer",new { Reference =
我通过存储过程使用
Dapper进行一些只读数据库调用.我有一个查询将返回1行或没有.
我正在使用这样的Dapper: using (var conn = new SqlConnection(ConnectionString)) { conn.Open(); return conn.Query<CaSEOfficer>("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是否可能返回空行?一排所有空值?或者它返回0行?
现在,假设没有返回任何行,如果CaSEOfficer是一个类,则FirstOrDefault(标准的LINQ-to-Objects事物)将返回null,如果CaSEOfficer是一个结构,则返回默认实例.接下来:检查CaSEOfficer是一个类(我想不出任何理智的结构). 但是:使用FirstOrDefault的小巧通常已经做到了你想要的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |