Getting an error when inserting multiple rows via Entity Framework 7

asp.net-core-mvc c# entity-framework entity-framework-core

Question

I have a simple table and a simple generated model to go along with it.

CREATE TABLE dbo.Admin (
     Id int IDENTITY(1, 1) NOT NULL
    ,DomainLogin nvarchar(50) NOT NULL
    ,CONSTRAINT PK_Admin PRIMARY KEY CLUSTERED (DomainLogin ASC)
)

When I attempt to add multiple entries via AddRange method (code below), it causes an error Incorrect syntax near ','.

var admins = new List<Admin>()
{
    new Admin() {DomainLogin = "zzz1"},
    new Admin() {DomainLogin = "zzz2"},
    new Admin() {DomainLogin = "zzz3"}
};

ctx.Admin.AddRange(admins);
ctx.SaveChanges();

I've also tried using the Add method:

ctx.Admin.Add(new Admin() {DomainLogin = "zzz1"});
ctx.Admin.Add(new Admin() {DomainLogin = "zzz2"});
ctx.Admin.Add(new Admin() {DomainLogin = "zzz3"});
ctx.SaveChanges();

However, if I save each individual item, like below, it works, but as you can imagine, it really slows down when there is a lot of rows:

ctx.Admin.Add(new Admin() {DomainLogin = "zzz1"});
ctx.SaveChanges();
ctx.Admin.Add(new Admin() {DomainLogin = "zzz2"});
ctx.SaveChanges();
ctx.Admin.Add(new Admin() {DomainLogin = "zzz3"});
ctx.SaveChanges();

Why am I getting an error?

I should mention that I am using Entity Framework 7 with asp.net 5 / mvc 6. The version of Entity Framework 7 is "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final"

P.S. I profiled the code and it generates the following SQL, which predictably gives the same error:

exec sp_executesql N'SET NOCOUNT OFF;
INSERT INTO [Admin] ([DomainLogin])
OUTPUT INSERTED.[Id]
VALUES (@p0),
(@p1),
(@p2);
',N'@p0 nvarchar(4000),@p1 nvarchar(4000),@p2 nvarchar(4000)',@p0=N'zzz1',@p1=N'zzz2',@p2=N'zzz3'

P.P.S This is against SQL Server 2005

Accepted Answer

SQL Server 2005 is not supported by Entity Framework 7 (in fact SQL Server 2005 is not supported by Microsoft any longer).

Specifically, the multi-row INSERT VALUES syntax used by EF7 is not supported, it requires SQL Server 2008 or newer.

See https://github.com/aspnet/EntityFramework/issues/3691

You may be able to work around it by setting a MaxBatchSize of 1



Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why