我正在将数据从 CSV 文件导入 SQL Server DB,CSV 可能包含重复条目。
我现有的代码使用 SqlBulkCopy() 和“IGNORE_DUP_KEY = ON”,所有重复都很好。
我首先使用 EF Core 和 Zzz Projects Entity Framework Extensions 切换到代码。
主键在 DbContext 中定义:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
if (modelBuilder == null)
throw new ArgumentNullException(nameof(modelBuilder));
modelBuilder.Entity<AmbientWeatherData>()
.HasKey(u => new { u.TimeStamp });
modelBuilder.Entity<ApcUpsData>()
.HasKey(u => new { u.TimeStamp });
modelBuilder.Entity<PurpleAirData>()
.HasKey(u => new { u.TimeStamp });
modelBuilder.Entity<Vr1710Data>()
.HasKey(u => new { u.TimeStamp });
modelBuilder.Entity<Vr1710EventData>()
.HasKey(u => new { u.TimeStamp, u.Type });
modelBuilder.Entity<WeatherGooseData>()
.HasKey(u => new { u.TimeStamp });
modelBuilder.Entity<WundergroundData>()
.HasKey(u => new { u.TimeStamp });
modelBuilder.Entity<WundergroundDailyData>()
.HasKey(u => new { u.TimeStamp });
}
使用 BulkInsert 插入数据:
dbContext.BulkInsert(data, options => options.AllowDuplicateKeys = true);
插入重复项时的异常:
Microsoft.Data.SqlClient.SqlException (0x80131904): Violation of PRIMARY KEY constraint 'PK_Vr1710Data'. Cannot insert duplicate key in object 'dbo.Vr1710Data'. The duplicate key value is (2014 - 12 - 28 14:26:07.0000000).
插入数据的函数是通用的并且类型不可知。
public static bool Import<TDataType, TLoaderType, TConfigType>(string fileName, string connectionString)
where TLoaderType : TelemetryLoader<TDataType, TConfigType>, new()
where TConfigType : TelemetryConfig
where TDataType : TelemetryData
{
// ...
}
BulkInsert()
的在线示例和 AllowDuplicateKeys
需要使用 ColumnPrimaryKeyExpression
发件人:https://entityframework-extensions.net/bulk-insert#insert-only-if-the-entity-not-already-existscontext.BulkInsert(customers, options => {
options.InsertIfNotExists = true;
options.ColumnPrimaryKeyExpression = c => c.Code;
});
如何在不需要特化的情况下忽略重复项
ColumnPrimaryKeyExpression
对于每种数据类型,而是使用 DbContext 中定义的我的键?
最佳答案
How can I ignore duplicates without needing a specialization for ColumnPrimaryKeyExpression for every data type, but instead use my keys as defined in the DbContext?
默认情况下,库已经从
DbContext
中获取 key 。 .在示例中,
c.Code
代表一个自定义键(CustomerID
是真正的键)。如果我正确理解问题,则需要使用以下代码:
context.BulkInsert(customers, options => {
options.InsertIfNotExists = true;
options.AllowDuplicateKeys = true;
});
这两个选项都是必需的。
关于c# - 如何使用 Entity Framework 扩展 BulkInsert 和 AllowDuplicateKeys,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60583568/