DapperLib / DapperLib/Dapper

Allow enumerable to be passed as a TVP

Open
#201 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement needs-review
Dominant language
C#
Stars
18.4k
Forks
3.7k
Avg merge
5h 8m
Merged PRs (30d)
1

Description

This is not an issue, but since I have no clue how to submit an enhancement, here I go ...

I'd like to submit for your consideration the following Extension to Dapper:

/// <summary>
/// This extension converts an enumerable set to a Dapper TVP
/// </summary>
/// <typeparam name="T">type of enumerbale</typeparam>
/// <param name="enumerable">list of values</param>
/// <param name="typeName">database type name</param>
/// <param name="orderedColumnNames">if more than one column in a TVP, columns order must mtach order of columns in TVP</param>
/// <returns>a custom query parameter</returns>
public static SqlMapper.ICustomQueryParameter AsTableValuedParameter<T>(this IEnumerable<T> enumerable,
    string typeName, IEnumerable<string> orderedColumnNames = null)
{
    var dataTable = new DataTable();
    if (typeof(T).IsValueType)
    {
        dataTable.Columns.Add("NONAME", typeof(T));
        foreach (T obj in enumerable)
        {
            dataTable.Rows.Add(obj);
        }                
    }
    else
    {
        PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        PropertyInfo[] readableProperties = properties.Where(w => w.CanRead).ToArray();
        if (readableProperties.Length > 1 && orderedColumnNames == null)
            throw new ArgumentException("Ordered list of column names must be provided when TVP contains more than one column");
        var columnNames = (orderedColumnNames ?? readableProperties.Select(s => s.Name)).ToArray();
        foreach (string name in columnNames)
        {
            dataTable.Columns.Add(name, readableProperties.Single(s => s.Name.Equals(name)).PropertyType);
        }

        foreach (T obj in enumerable)
        {
            dataTable.Rows.Add(
                columnNames.Select(s => readableProperties.Single(s2 => s2.Name.Equals(s)).GetValue(obj))
                    .ToArray());
        }
    }
    return dataTable.AsTableValuedParameter(typeName);
}

Sample uses:

var l = new List<AUDITRECORD>
{
    new AUDITRECORD {AUDIT_PK = 2, MESSAGE = "HELO", SUCCESS = true},
    new AUDITRECORD {AUDIT_PK = 3, MESSAGE = "EHLO", SUCCESS = false}
};

using (var conn = new SqlConnection(connString))
{
    conn.Open();
    conn.Execute("TestOne",
        new { TVP = l.AsTableValuedParameter("AuMine.AUDITRECORD", new[] { "AUDIT_PK", "MESSAGE", "SUCCESS" }) },
        commandType: CommandType.StoredProcedure);
}

var customerKeys = new List<long>{3,5,7};
var productKeys = new List<long>{11,33,55};

using (var conn = new SqlConnection("Data Source=.;Initial Catalog=Scratch;Integrated Security=true"))
{
    conn.Open();
    conn.Execute("TestTwo",
        new
        {
            customerKeys = customerKeys.AsTableValuedParameter("dbo.TVPBIGINT"),
            productKeys = productKeys.AsTableValuedParameter("dbo.TVPBIGINT")
        },
        commandType: CommandType.StoredProcedure);
}

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No repository files or tests are named. Start by reviewing Dapper's existing AsTableValuedParameter support alongside the supplied extension and examples, then identify the appropriate integration point and verify scalar and multi-column enumerable TVPs with tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
csharp, sql
Domain
database
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.