【问题标题】:Insert/Update bulk data to sql table in entity framework在实体框架中将批量数据插入/更新到 sql 表
【发布时间】:2016-06-10 13:41:51
【问题描述】:

我有一个产品表,其中包含产品编号、价格和货币。 我通过带有数据的excel文件上传数据。 当我上传数据时,我会在后端创建一个包含所有来自 excel 数据的列表,然后将整个列表发送到服务器以更新/插入表中的数据。

               foreach(Product value in item)
                {
                    Product p = context.Product.SingleOrDefault(p => p.ProductNumber == value.ProductNumber && p.CurrencyId == value.CurrencyId);
                    if (p!= null)
                    {

                        context.Entry<Product>(p).Property(p => p.ProductPrice).IsModified = true;
                        p.ProductPrice = value.ProductPrice ;

                        context.SaveChanges();
                    }
                    else
                    {

                        context.Product.Add(value);
                        context.SaveChanges();
                    }
                }

但是随着数据的增加(产品的增加),上传需要很多时间。 有什么建议可以优化吗?我在想的一件事是关于产品编号和货币列的索引。

【问题讨论】:

    标签: entity-framework-6 bulkinsert bulkupdate


    【解决方案1】:

    性能问题不是因为索引引起的(当然,如果不存在索引,这也会有所帮助),而是因为您的代码正在执行的数据库往返次数。

    对于每个产品:

    • 您检查产品是否存在(1 个数据库往返)
    • 您插入/更新产品(1 次数据库往返)

    因此,如果您从 excel 文件中上传 10,000 个产品,您将执行 20,000 个数据库往返,这太疯狂了。

    有些技巧可能有助于提高性能,例如使用 AddRange 而不是 Add 添加要插入的多个产品,但您最终会遇到由数据库往返次数引起的相同性能问题。

    免责声明:我是项目的所有者Entity Framework Extensions

    这个库允许通过执行来显着提高性能:

    • 批量保存更改
    • 批量插入
    • 批量更新
    • 批量删除
    • 批量合并

    例子:

    // Insert or Update using ProductNumber && CurrencyId as the Key
    ctx.BulkMerge(list, operation =>
    {
        operation.ColumnPrimaryKeyExpression = x => new {x.ProductNumber, x.CurrencyId};
    });
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2014-06-12
    • 1970-01-01
    相关资源
    最近更新 更多