Fastest Way of Inserting in Entity Framework

前端 未结 30 2197
鱼传尺愫
鱼传尺愫 2020-11-21 05:23

I\'m looking for the fastest way of inserting into Entity Framework.

I\'m asking this because of the scenario where you have an active TransactionScope a

30条回答
  •  再見小時候
    2020-11-21 05:37

    Yes, SqlBulkUpdate is indeed the fastest tool for this type of task. I wanted to find "least effort" generic way for me in .NET Core so I ended up using great library from Marc Gravell called FastMember and writing one tiny extension method for entity framework DB context. Works lightning fast:

    using System.Collections.Generic;
    using System.Linq;
    using FastMember;
    using Microsoft.Data.SqlClient;
    using Microsoft.EntityFrameworkCore;
    
    namespace Services.Extensions
    {
        public static class DbContextExtensions
        {
            public static void BulkCopyToServer(this DbContext db, IEnumerable collection)
            {
                var messageEntityType = db.Model.FindEntityType(typeof(T));
    
                var tableName = messageEntityType.GetSchema() + "." + messageEntityType.GetTableName();
                var tableColumnMappings = messageEntityType.GetProperties()
                    .ToDictionary(p => p.PropertyInfo.Name, p => p.GetColumnName());
    
                using (var connection = new SqlConnection(db.Database.GetDbConnection().ConnectionString))
                using (var bulkCopy = new SqlBulkCopy(connection))
                {
                    foreach (var (field, column) in tableColumnMappings)
                    {
                        bulkCopy.ColumnMappings.Add(field, column);
                    }
    
                    using (var reader = ObjectReader.Create(collection, tableColumnMappings.Keys.ToArray()))
                    {
                        bulkCopy.DestinationTableName = tableName;
                        connection.Open();
                        bulkCopy.WriteToServer(reader);
                        connection.Close();
                    }
                }
            }
        }
    }
    

提交回复
热议问题