首页 > 解决方案 > Z.EntityFramework.Extensions.EFCore BulkMerge - 非键索引以更新大量记录

问题描述

我有需要更新大量记录的情况。然而,mytable 是非常动态的,它的主键是 DBGenerated。我想知道是否有人使用 EF Extensions 来完成基于其他字段的更新。我已经从他们的文档中尝试了以下内容,但它没有映射,只是重新插入了很多。我曾多次尝试修改选项,但没有太大成功。我需要将“更新键”映射为其他三列,保留原始 PK。有人能在保持速度的同时提出更好的路线吗?..我真的不想循环并一次手动更新每一个

https://bulk-operations.net/bulk-merge

await _db.Enotes.BulkMergeAsync(orderEnotes, operation =>
{
    operation.AutoMapKeyExpression = prop => new { prop.Entity, prop.EnoteType, prop.KeyValue1 };
    operation.InsertIfNotExists = true;
    operation.InsertKeepIdentity = false;
});

班级

public class EnoteEntity
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Int64 EnoteID { get; set; }

        public string Entity { get; set; }

        public string EnoteType { get; set; }

        public string KeyValue1 { get; set; }

        public string KeyValue2 { get; set; }

Code removed for brevity... 

标签: mergeentity-framework-coreentity-framework-extensions

解决方案


您当前使用该库Entity Framework Extensions,但您正在查看Bulk Operations文档,因此存在一些差异。

这是关于批量合并的正确文档:https ://entityframework-extensions.net/bulk-merge

正如您将发现的那样,您不应该使用AutoMapKeyExpression而是ColumnPrimaryKeyExpression指定自定义键(在线示例):

await _db.Enotes.BulkMergeAsync(orderEnotes, operation =>
{
    operation.ColumnPrimaryKeyExpression = prop => new { prop.Entity, prop.EnoteType, prop.KeyValue1 };
});

此外,

该选项InsertIfNotExists仅适用于BulkInsert并且InsertKeepIdentity默认情况下已经为 false。


推荐阅读