EntityFrameworkCore不批处理插入

时间:2019-07-14 13:23:31

标签: c# entity-framework-core-2.2

在EntityFrameworkCore上学习PluralSight课程之一时,我从视频中看到了不同的结果。即,在依次调用DbSet<...>.AddRange(item 1, item2)DbSet<...>.SaveChanges时,我看到两个简单的INSERT语句,而不是一个复杂的INSERT语句。

要在Visual Studio 2017中重新创建它,

  1. 使用C#4.7.2创建一个新的.NET Framework Console App。将其命名为 SomeUI
  2. 在程序包管理器控制台中运行以下命令
    • Install-Package Microsoft.Extensions.Logging.Console SomeUI -Version 2.2.0
    • Install-Package Microsoft.EntityFrameworkCore.SqlServer SomeUI -Version 2.2.6
    • Install-Package Microsoft.EntityFrameworkCore.Tools SomeUI -Version 2.2.6
  3. 将以下代码粘贴为Program.cs。
  4. 在程序包管理器控制台中运行以下命令
    • Add-Migration initial
    • Update-Database

Program.cs:

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;

namespace SomeUI
{
    public class Samurai
    {
        public String Name { get; set; }
        public int Id { get; set; }
    }

    public class SamuraiContext : DbContext
    {
        public DbSet<Samurai> Samurais { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder
                .UseLoggerFactory(new ServiceCollection()
                    .AddLogging(builder => builder
                        .AddConsole()
                        .AddFilter(DbLoggerCategory.Database.Command.Name, LogLevel.Information))
                    .BuildServiceProvider()
                    .GetService<ILoggerFactory>())
                .UseSqlServer("Server = (localdb)\\mssqllocaldb; Database = SamuraiAppData; Trusted_Connection = True; ");
        }

        static void Main(string[] args)
        {
            using (var context = new SamuraiContext())
            {
                context.Samurais.AddRange(new Samurai { Name = "Jack" }, new Samurai { Name = "Jill" });
                context.SaveChanges();
            }
        }
    }
}

我所看到的:

info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 2.2.6-servicing-10079 initialized 'SamuraiContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer' with options: None
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (18ms) [Parameters=[@p0='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
      SET NOCOUNT ON;
      INSERT INTO [Samurais] ([Name])
      VALUES (@p0);
      SELECT [Id]
      FROM [Samurais]
      WHERE @@ROWCOUNT = 1 AND [Id] = scope_identity();
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (1ms) [Parameters=[@p0='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
      SET NOCOUNT ON;
      INSERT INTO [Samurais] ([Name])
      VALUES (@p0);
      SELECT [Id]
      FROM [Samurais]
      WHERE @@ROWCOUNT = 1 AND [Id] = scope_identity();

我应该看到的:

info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (18ms) [Parameters=[@p0='?' (Size = 4000)], @p1='?' (Size=4000)], CommandType='Text', CommandTimeout='30']
      SET NOCOUNT ON;
      DECLARE @inserted0 TABLE ([Id] int, [_Position] [int]);
      MERGE [Samurais] USING (
      VALUES (@p0, 0),
      (@p1, 1)) AS i ([Name], _Position) ON 1=0
      WHEN NOT MATCHED THEN
      INSERT ([Name])
      VALUES (i.[Name])
      OUTPUT INSERTED.[Id], i._Position
      INTO @inserted0;

      SELECT [t].[Id] FROM [Samurais] t
      INNER JOIN @inserted0 i ON ([t].[Id] = [i].[Id])
      ORDER BY [i].[_Position];

任何想法可能出什么问题吗?在此先感谢可以帮助我在此获得一些见识的任何人。

1 个答案:

答案 0 :(得分:4)

好的,这是我最喜欢的答案。

您根本没有足够的武士。尝试七个:

  context.Samurais.AddRange(
         new Samurai { Name = "Kambei Shimada" }, 
         new Samurai { Name = "Gorōbei Katayama" },
         new Samurai { Name = "Shichirōji" },
         new Samurai { Name = "Kyūzō" },
         new Samurai { Name = "Heihachi Hayashida" },
         new Samurai { Name = "Katsushirō Okamoto" },
         new Samurai { Name = "Kikuchiyo" }
         );

您将看到命令批处理启动:

info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (210ms) [Parameters=[@p0='?' (Size = 4000), @p1='?' (Size = 4000), @p2='?' (Size = 4000), @p3='?' (Size = 4000), @p4='?' (Size = 4000), @p5='?' (Size = 4000), @p6='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
      SET NOCOUNT ON;
      DECLARE @inserted0 TABLE ([Id] int, [_Position] [int]);
      MERGE [Samurais] USING (
      VALUES (@p0, 0),
      (@p1, 1),
      (@p2, 2),
      (@p3, 3),
      (@p4, 4),
      (@p5, 5),
      (@p6, 6)) AS i ([Name], _Position) ON 1=0
      WHEN NOT MATCHED THEN
      INSERT ([Name])
      VALUES (i.[Name])
      OUTPUT INSERTED.[Id], i._Position
      INTO @inserted0;

      SELECT [t].[Id] FROM [Samurais] t
      INNER JOIN @inserted0 i ON ([t].[Id] = [i].[Id])
      ORDER BY [i].[_Position];

您可以在DbContext的OnConfiguring方法中的SqlServerDbContextOptionsBuilder上配置最小或最大批处理大小。