使用 Dapper 发送和接收数据表

Send and receive Datatable using Dapper

我在另一个模型中有一个模型,例如:

第一个模型:

public class ReminderPushNotificationTest
{
    public string UserName { get; set; }
    ....
    public ReminderPushNotificationTableType AndroidResultTableType { get; set; }
}

第二个模型:

public class ReminderPushNotificationTableType
{
    public string Headers { get; set; }
    ...
}

在 SQL 中,我创建了一个 table 值参数并将其作为我的存储过程中的参数接收:

 @AndroidResultTableType [HELPER].[PushNotificationTestTableType] READONLY

我使用 Dapper 发送结果为:

public async Task<bool> ReminderPushNotificationInsert_Test(ReminderPushNotificationTest model)
{
    try
    {
        async Task<bool> DoReminderPushNotificationInsert_Test()
        {
            using var connection = _connectionManager.GetOpenConnection(_configuration.GetConnectionString(ConnectionString));

            await connection.QueryAsync("[Test].[usp_spName]", param: new {
                model.UserId,
                model.AndroidResultTableType
            }
            , commandType: CommandType.StoredProcedure);

            return true;
        }
        return await DoReminderPushNotificationInsert_Test();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

但是抛出异常:

The member AndroidResultTableType of type Models.Helpers.Test.ReminderPushNotificationTableType cannot be used as a parameter value

如果 AndroidResultTableType 不是列表,我如何将其作为数据 table 传递。它总是有 1 行。

您需要构造 DataTable 并填充其字段,而不是直接传递对象

await connection.QueryAsync("[Test].[usp_spName]", new
{
    model.UserId,
    AndroidResultTableType = CreateTableType(model.AndroidResultTableType)
}, commandType: CommandType.StoredProcedure);

private static DataTable CreateTableType(
    ReminderPushNotificationTableType notification)
{
    var t = new DataTable();
    t.SetTypeName("[HELPER].[PushNotificationTestTableType]");
    t.Columns.Add("Headers");
    t.Rows.Add(notification.Headers);
    return t;
}