Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - How to return null from a Dapper query rather than default(T)?

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

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

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: "[email protected]",
    telephone: "01234 567890"
}

But when it returns nothing I get:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?

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).

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...