如何从一个小巧玲珑的查询,而不是默认的(T)返回null? [英] How to return null from a Dapper query rather than default(T)?

查看:243
本文介绍了如何从一个小巧玲珑的查询,而不是默认的(T)返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用通过存储过程的一些只读数据库调用小巧玲珑。 。我有一个查询,或者返回1行或没有

I'm using Dapper for some read-only database calls via a stored procedure. I've got a query that will either return 1 row or nothing.

我使用的是小巧玲珑的是这样的:

I'm using Dapper like this:

using (var conn = new SqlConnection(ConnectionString))
{
    conn.Open();

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



返回的CaseOfficer对象是这样的:

The returned CaseOfficer object looks like this:

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返回。

This is then returned through a ASP.NET Web API application as JSON.

在存储过程返回一个结果我得到了以下内容:

When the stored procedure returns a 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
}

我怎样才能得到小巧玲珑返回空值(这样我就可以检查并与404响应),而不是默认的(CaseOfficer)?

How can I get Dapper to return null (so I can check and respond with 404), rather than the default(CaseOfficer)?

推荐答案

如果您SP不返回行,那么短小精悍不会返回一行;所以首先要检查:你的SP或许返回一个空行?所有的 S的行?还是因为它返回0行?

If your SP doesn't return a row, then dapper won't return a row; so first thing to check: did your SP perhaps return an empty row? A row of all nulls ? Or did it return 0 rows?

现在,假设没有返回的行, FirstOrDefault (标准LINQ到-Objects东西)将返回如果 CaseOfficer ,或 CaseOfficer 是结构。因此,下:检查 CaseOfficer (我想不出任何理由理智,这将是一个结构

Now, assuming no row was returned, FirstOrDefault (the standard LINQ-to-Objects thing) will return null if CaseOfficer is a class, or a default instance if CaseOfficer is a struct. So next: check CaseOfficer is a class (I can't think of any sane reason that would be a struct).

不过:短小精悍与 FirstOrDefault 一般已经做的你想要什么。

But: dapper with FirstOrDefault will generally already do what you want.

这篇关于如何从一个小巧玲珑的查询,而不是默认的(T)返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆