Michael
Michael

Reputation: 245

Use the Dapper to return the date if the value is in null basis

how can I use Dapper to return the date if I have this field in NULL?

This is my method, only something is missing when I return the output to the method, see the picture .. I do not know what I'm doing wrong ..

My method:

    public DateTime GetArbeitStart(int userId)
    {
        using (IDbConnection connection = new System.Data.SqlClient.SqlConnection())
        {
            connection.ConnectionString = _ConnectionString;
            var output = connection.Query<DateTime>("select LPE_ArbeitStart from A_PERSONAL WHERE LPE_ID=" + userId).FirstOrDefault();

            return output == null ? new DateTime(2018, 1, 1);
        } 
    }

enter image description here

Upvotes: 1

Views: 1205

Answers (3)

Palle Due
Palle Due

Reputation: 6312

Here is another alternative:

public DateTime GetArbeitStart(int userId)
{
    using (IDbConnection connection = new System.Data.SqlClient.SqlConnection())
    {
        connection.ConnectionString = _ConnectionString;
        return connection.Query<DateTime>("select LPE_ArbeitStart from A_PERSONAL WHERE LPE_ID=" + userId)
            .DefaultIfEmpty(new DateTime(2018, 1, 1)).First();
    } 
}

I like that it's really declarative.

Upvotes: 0

Andrei Piatrou
Andrei Piatrou

Reputation: 434

you are missing else part in a ternary operator

return output === null ? new Date() : somethingElse;

Upvotes: 1

ProgrammingLlama
ProgrammingLlama

Reputation: 38850

As far as I can tell, you seem to be trying to combine a ternary operator with the null coalescing operator.

I think you simply want the null coalescing operator:

return output ?? new DateTime(2018, 1, 1); 

Or if you want the more verbose ternary operator:

return output == null ? new DateTime(2018, 1, 1) : output;

Upvotes: 3

Related Questions