我创建了一个小项目,允许用户通过 Entity-Framework 将 CSV 文件导入 SQL。主要程序如下所示:
using (TextFieldParser tx = new TextFieldParser(file, Encoding.UTF8))
{
tx.TextFieldType = FieldType.Delimited;
tx.SetDelimiters(";");
tx.ReadLine(); //The First Line are the headers, no need
while (!tx.EndOfData)
{
decimal decTmp;
int intTmp;
string[] fields = tx.ReadFields();
//Convert every field to the appropriate type, tryparse if nullable
ReportInfo("Verarbeite Nummer: " + fields[(int)ConnectionEvaluationFileField.PhoneNumber].Trim());
Verbindunganalyse con = new Verbindunganalyse();
con.Auswertungszeitraum = fields[(int)ConnectionEvaluationFileField.EvaluationTimeSpan].TrimStart('0');
con.Betrag_inkl_MWST_CHF = Decimal.Parse(fields[(int)ConnectionEvaluationFileField.Cost]);
if (decimal.TryParse(fields[(int)ConnectionEvaluationFileField.DataInMb], out decTmp))
con.Daten_MB = decTmp;
con.Durchwahlnummer = Int64.Parse(fields[(int)ConnectionEvaluationFileField.PhoneNumber]);
con.Produkteigenschaft = fields[(int)ConnectionEvaluationFileField.ProductProperty];
if (Int32.TryParse(fields[(int)ConnectionEvaluationFileField.Messages], out intTmp))
con.SMS_MMS_Anzahl = intTmp;
con.TelefonieDauer = TimeSpan.Parse(fields[(int)ConnectionEvaluationFileField.CallLength]);
con.Untergruppe = fields[(int)ConnectionEvaluationFileField.SubGroup];
if (Int32.TryParse(fields[(int)ConnectionEvaluationFileField.Connections], out intTmp))
con.Verbindungen_Anzahl = intTmp;
container.Verbindunganalyse.Add(con);
}
}
这是德语,但我认为代码非常清晰:我使用 TextFieldParser 读取数据,创建一个新的实体并将字段解析/检查到属性中。
问题:客户曾经有一个 Access-Solution,需要大约 20-30 秒来导入数据,使用我的解决方案,我需要大约 2-3 分钟来导入 2 个文件和 5k 数据集。
我发现了一些类似 https://efbulkinsert.codeplex.com/ 的 BulkInsert ,但我们在这里谈论的是两个文件中的大约 10k 数据集。
我删除了 ReportInfo 等,但我看不出有什么方法可以使这项工作更快。您是否认为有可能使用 EF 使这些东西更快?还是 TextFieldParser 非常慢,我需要在那里检查?
最佳答案
我知道这是一篇旧帖子,但我自己一直在试验。我尝试了 Entity Framework Seeder NuGet package和一个 bare-metal SQL bulk insert使用以下代码;
CREATE TABLE [dbo].[TempTable] (
[Field] type constraints,
etc...
)
GO
BULK INSERT TempTable FROM 'filePath' WITH (
FIRSTROW = 2,
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\r\n'
)
GO
INSERT INTO [FinalTable] SELECT [Fields] FROM [TempTable]
GO
DROP TABLE [TempTable]
seeder 方法在 67 秒内插入 10,000 条记录,而批量插入方法需要 223 毫秒。这真的很简单。
关于c# - 将 CSV 导入 SQL-Server - 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25668541/