Call stored procedure from dapper which accept list of user defined table type

懵懂的女人 提交于 2019-12-03 01:56:57

My problem is also that I have cars in generic list List Cars and I want pass this list to store procedure. It exist elegant way how to do it ?

You need to convert your generic list Car to a datatable and then pass it to storedprocedure. A point to note is that the order of your fields must be same as defined in the user defined table type in database. Otherwise data will not save properly. And it must have same number of columns as well.

I use this method to convert List to DataTable. You can call it like yourList.ToDataTable()

public static DataTable ToDataTable<T>(this List<T> iList)
    {
        DataTable dataTable = new DataTable();
        PropertyDescriptorCollection propertyDescriptorCollection =
            TypeDescriptor.GetProperties(typeof(T));
        for (int i = 0; i < propertyDescriptorCollection.Count; i++)
        {
            PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
            Type type = propertyDescriptor.PropertyType;

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                type = Nullable.GetUnderlyingType(type);


            dataTable.Columns.Add(propertyDescriptor.Name, type);
        }
        object[] values = new object[propertyDescriptorCollection.Count];
        foreach (T iListItem in iList)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
            }
            dataTable.Rows.Add(values);
        }
        return dataTable;
    }

I know this is a little old, but I thought I would post on this anyway since I sought out to make this a little easier. I hope I have done so with a NuGet package I create that will allow for code like:

public class CarType
{
  public int CARID { get; set; }
  public string CARNAME{ get; set; }
}

var cars = new List<CarType>{new CarType { CARID = 1, CARNAME = "Volvo"}};

var parameters = new DynamicParameters();
parameters.AddTable("@Cars", "CarType", cars)

 var result = con.Query("InsertCars", parameters, commandType: CommandType.StoredProcedure);

NuGet package: https://www.nuget.org/packages/Dapper.ParameterExtensions/0.2.0 Still in its early stages so may not work with everything!

Please read the README and feel free to contribute on GitHub: https://github.com/RasicN/Dapper-Parameters

The other solution would be to call it like this

var param = new DynamicParameters(new{CARID= 66, CARNAME= "Volvo"});

var result = con.Query<dynamic>("InsertCars", param);

Remove : new CarDynamicParam(car), commandType: CommandType.StoredProcedure

Use the parameter of table type directly, it will work.

If you can use Datatable(.net core does not support it), then its very easy.

Create DataTable -> Add required columns to match with your table type -> Add required rows. Finally just call it using dapper like this.

var result = con.Query<dynamic>("InsertCars", new{paramFromStoredProcedure=yourDataTableInstance}, commandType: CommandType.StoredProcedure);

Using reflection to map object properties to datatable columns is expensive. Taking Ehsan's solution further, where performance is a concern you can cache the type property mappings. As Ehsan also pointed out, the order in the class must be the same as in the database and there must be an equal number of columns. This can be overcome by reordering the columns according to the type definition.

public static class DataTableExtensions
{
    private static readonly EntityPropertyTypeMap PropertyTypeMap = new EntityPropertyTypeMap();

    public static DataTable ToDataTable<T>(this ICollection<T> values)
    {
        if (values is null)
        {
            throw new ArgumentNullException(nameof(values));
        }

        var table = new DataTable();

        var properties = PropertyTypeMap.GetPropertiesForType<T>().Properties;

        foreach (var prop in properties)
        {
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        }

        foreach (var value in values)
        {
            var propertyCount = properties.Count();
            var propertyValues = new object[propertyCount];

            if (value != null)
            {
                for (var i = 0; i < propertyCount; i++)
                {
                    propertyValues[i] = properties[i].GetValue(value);
                }
            }

            table.Rows.Add(propertyValues);
        }

        return table;
    }
}


public static class DapperExtensions
{
    private static readonly SqlSchemaInfo SqlSchemaInfo = new SqlSchemaInfo();

    public static DataTable ConvertCollectionToUserDefinedTypeDataTable<T>(this SqlConnection connection, ICollection<T> values, string dataTableType = null)
    {
        if (dataTableType == null)
        {
            dataTableType = typeof(T).Name;
        }

        var data = values.ToDataTable();

        data.TableName = dataTableType;

        var typeColumns = SqlSchemaInfo.GetUserDefinedTypeColumns(connection, dataTableType);

        data.SetColumnsOrder(typeColumns);

        return data;
    }

    public static DynamicParameters AddTableValuedParameter(this DynamicParameters source, string parameterName, DataTable dataTable, string dataTableType = null)
    {
        if (dataTableType == null)
        {
            dataTableType = dataTable.TableName;
        }

        if (dataTableType == null)
        {
            throw new NullReferenceException(nameof(dataTableType));
        }

        source.Add(parameterName, dataTable.AsTableValuedParameter(dataTableType));

        return source;
    }

    private static void SetColumnsOrder(this DataTable table, params string[] columnNames)
    {
        int columnIndex = 0;

        foreach (var columnName in columnNames)
        {
            table.Columns[columnName].SetOrdinal(columnIndex);
            columnIndex++;
        }
    }
}

class EntityPropertyTypeMap
{
    private readonly ConcurrentDictionary<Type, TypePropertyInfo> _mappings;

    public EntityPropertyTypeMap()
    {
        _mappings = new ConcurrentDictionary<Type, TypePropertyInfo>();
    }

    public TypePropertyInfo GetPropertiesForType<T>()
    {
        var type = typeof(T);
        return GetPropertiesForType(type);
    }

    private TypePropertyInfo GetPropertiesForType(Type type)
    {
        return _mappings.GetOrAdd(type, (key) => new TypePropertyInfo(type));
    }
}


class TypePropertyInfo
{
    private readonly Lazy<PropertyInfo[]> _properties;
    public PropertyInfo[] Properties => _properties.Value;

    public TypePropertyInfo(Type objectType)
    {
        _properties = new Lazy<PropertyInfo[]>(() => CreateMap(objectType), true);
    }

    private PropertyInfo[] CreateMap(Type objectType)
    {
        var typeProperties = objectType
            .GetProperties(BindingFlags.DeclaredOnly |
                           BindingFlags.Public |
                           BindingFlags.Instance)
            .ToArray();

        return typeProperties.Where(property => !IgnoreProperty(property)).ToArray();
    }

    private static bool IgnoreProperty(PropertyInfo property)
    {
        return property.SetMethod == null || property.GetMethod.IsPrivate || HasAttributeOfType<IgnorePropertyAttribute>(property);
    }

    private static bool HasAttributeOfType<T>(MemberInfo propInfo)
    {
        return propInfo.GetCustomAttributes().Any(a => a is T);
    }
}

public class SqlSchemaInfo
{
    private readonly ConcurrentDictionary<string, string[]> _udtColumns = new ConcurrentDictionary<string, string[]>();

    public string[] GetUserDefinedTypeColumns(SqlConnection connection, string dataTableType)
    {
        return _udtColumns.GetOrAdd(dataTableType, (x) =>
            connection.Query<string>($@"
                    SELECT name FROM 
                    (
                        SELECT column_id, name
                        FROM sys.columns
                        WHERE object_id IN (
                          SELECT type_table_object_id
                          FROM sys.table_types
                          WHERE name = '{dataTableType}'
                        )
                    ) Result
                    ORDER BY column_id").ToArray());
    }
}


[AttributeUsage(AttributeTargets.Property)]
public sealed class IgnorePropertyAttribute : Attribute
{

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!