gpt4 book ai didi

c# - 改进 Entity Framework 插入

转载 作者:太空宇宙 更新时间:2023-11-03 15:33:37 26 4
gpt4 key购买 nike

我已经处理这个问题 2 天了,我找不到解决方案。

using (TaxablePersonContext context = new TaxablePersonContext(this.ConnectionString))
{
context.Configuration.AutoDetectChangesEnabled = false;
foreach(TaxablePerson p in persons) // Persons has always size 1000
{
// TaxablePerson has some other properties e.g. Name, VatId, Street,...
p.RecCreatedBy = "application name";
p.RecCreatedOn = this.SynchronizationStartDateTime;
p.RecModifiedBy = "application name";
p.RecModifiedOn = this.SynchronizationStartDateTime;
p.RecSyncDate = this.SynchronizationStartDateTime;
p.RecActive = true;
}
DateTime start1 = DateTime.Now;
context.TaxablePersons.AddRange(persons);
TimeSpan end1 = DateTime.Now.Subtract(start1);

DateTime start2 = DateTime.Now;
context.SaveChanges();
TimeSpan end2 = DateTime.Now.Subtract(start1);
}

我在 sql server 中插入 1000 条记录需要将近 10 秒,插入 10.000 条记录需要 98 秒。您能否建议如何提高 Entity Framework 插入性能。我读了这篇文章Fastest Way of Inserting in Entity Framework并包含了这篇文章中提到的提示,但插入速度仍然很慢。我需要插入 260.000 条记录,这需要 52 分钟。我正在插入 1000 个批处理,上面的代码演示了这一点。数据是从文件中读取的,当我达到 1000 条记录时,我会与数据库同步。我还可以做些什么?有人提到在使用时设置 context.Configuration.AutoDetectChangesEnabled = false;性能从几分钟提高到几秒钟。我错过了什么?我正在使用 Entity Framework 6.1.3。

最佳答案

使用 sql profiler,我发现 Entity 框架会一个接一个地发送查询,例如

INSERT INTO MyTable (id, name) VALUES (1, 'Bob')
INSERT INTO MyTable (id, name) VALUES (2, 'Peter')
INSERT INTO MyTable (id, name) VALUES (3, 'Joe')

所以实际上 sql server 在这种情况下执行 1000 个插入非常慢 - 将近 10 秒(尽管在事务中执行)。然后我构造了具有多个值的插入 - 具有许多值的 SQL 和 1000 条记录的插入花费了 5 秒(50%更好 - 更早的 10 秒)。 SQL Server 对您可以传递的 SQL 参数有限制,即 2100,因此这是您可以使用此方法做的最好的事情。

private void MultiRecordsInsert(TaxablePersonContext context, List<TaxablePerson> personsToAdd)
{
List<SqlParameter> parameters = new List<SqlParameter>();
string firstQuery = @"insert into TaxablePerson (c1, c2, c3) values ";
string query = firstQuery;

for (int i = 0; i < personsToAdd.Count; i++)
{
query += "(@c1" + i.ToString();
query += ",@c2" + i.ToString();
query += ",@c3" + i.ToString() + "),";
parameters.Add(new SqlParameter("@c1" + i.ToString(), personsToAdd[i].c1));
parameters.Add(new SqlParameter("@c2" + i.ToString(), personsToAdd[i].c2));
parameters.Add(new SqlParameter("@c3" + i.ToString(), personsToAdd[i].c3));

// table has 16 columns (I reduced here for simplicity) so: 2100 / 16 = 131,
// used 100
//
if (i % 100 == 0)
{
query = query.Substring(0, query.Length - 1); // remove last comma
context.Database.ExecuteSqlCommand(query, parameters.ToArray());

query = firstQuery;
parameters = new List<SqlParameter>();
}
}

if (parameters.Count > 0) // what is left
{
query = query.Substring(0, query.Length - 1);
context.Database.ExecuteSqlCommand(query, parameters.ToArray());
}
}

关于c# - 改进 Entity Framework 插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32716361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com