c# - 如何使用 Entity Framework 扩展 BulkInsert 和 AllowDuplicateKeys

标签 c# .net-core entity-framework-core

我正在将数据从 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-exists
context.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/

相关文章:

c# - 结构中需要重写什么以确保相等性正常运行?

c# - VS 在 'Set As StartUp Project' 后崩溃

c# - .NET Core 无法连接到远程 SQL Server 数据库

c# - “ConfigurationBuilder”不包含 'AddJsonFile' 的定义

c# - 带标志的 System.Enum 组合

angular - 如何将带有 Angular 表单数据的对象列表发布到 .Net Core Web API

c# - Linq 选择模型并设置属性

c# - 从 Entity Framework Core IQueryable<T> 获取 SQL 代码

c# - 调用 MySql 存储过程,它从 asp.net core 2.2 web API Controller 获取 2 个参数

c# - ASP.Net 从 ActionLink 打开模式