【问题标题】:List to datatable conversion takes more time列表到数据表的转换需要更多时间
【发布时间】:2018-08-29 03:19:13
【问题描述】:

使用 Entity Framework 将列表(即通用列表)传递给存储过程的最佳方式是什么。

我正在使用的当前解决方案将列表转换为DataTable,然后将其传递给存储过程。

下面显示的代码用于将通用列表转换为数据表,但处理大约 100000 条具有 6 个属性的对象记录大约需要 10 秒。

    public static DataTable ToDataTable<T>(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;
    }

我需要一些最好的方法来使用更少的时间将值列表传递给存储过程。

【问题讨论】:

  • 你用的是什么数据库?
  • SQL Server 2012
  • 我只使用了类似的方法(传递数据表)
  • 你能检查一下 10 秒的时间在哪里使用吗? iList 或 GetValue 上的 foreach 循环?拥有通用解决方案固然很好,但在这种情况下,一对一的属性映射可能会更有帮助。我过去曾遇到过类似的情况,并且使用硬编码映射与使用反射的初始通用解决方案相比,我设法将映射时间从大约 350 毫秒减少到 32 毫秒。

标签: c# sql-server entity-framework linq datatable


【解决方案1】:

我会通过创建用户定义的表类型来做到这一点。我认为这样会更好更快。

来源:[https://stackoverflow.com/questions/7097079/c-sharp-sql-server-passing-a-list-to-a-stored-procedure][1]

【讨论】:

    猜你喜欢
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 2022-01-02
    相关资源
    最近更新 更多