ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

SqlClient wrapper for reading DateOnly

A wrapper to work with DateOnly for a SqlDataReader which is available starting with .NET Core 6. The example as an aside shows a secondary extension for asynchronous read for strings.

Source

sing Microsoft.Data.SqlClient;

namespace TODO;

public static class SqlClientExtensions
{
    public static async Task<DateOnly> GetDateOnlyAsync(this SqlDataReader reader, int index)
        => await reader.GetFieldValueAsync<DateOnly>(index);
    public static async Task<string> GetStringAsync(this SqlDataReader reader, int index)
        => await reader.GetFieldValueAsync<string>(index);
}

Example

public class Demo
{
    public static async Task<Person> Get(int id)
    {
        await using SqlConnection cn = new("TODO");
        await using SqlCommand cmd = new()
        {
            Connection = cn,
            CommandText = """
                          SELECT Id,
                                 FirstName,
                                 LastName,
                                 BirthDate
                          FROM dbo.Person
                          WHERE Id = @Id;
                          """
        };

        cmd.Parameters.Add("@Id", SqlDbType.Int).Value = id;

        await cn.OpenAsync();
        SqlDataReader reader = await cmd.ExecuteReaderAsync();
        await reader.ReadAsync();

        Person person = new()
        {
            Id = id,
            FirstName = await reader.GetStringAsync(1),
            LastName = await reader.GetStringAsync(2),
            BirthDate = await reader.GetDateOnlyAsync(3)
        };

        return person;
    }
}

Author: Karen Payne

Submitted on: 30 jul. 2024

Language: csharp

Type: Microsoft.Data.SqlClient

Views: 370