Search code examples
c#entity-frameworksql-server-ce

C# Exception while executing sqlCE query


When I am running this script manual it is working but when I am running it in c# with Entity Framework I am getting an exception

db.Database.ExecuteSqlCommand(script); //Exception 

Sql script:

CREATE TABLE [Customers]
(
   [Id] INT NOT NULL IDENTITY (1,1),
   [Name] NVARCHAR(4000) NOT NULL,
   [Email] NVARCHAR(4000) NOT NULL,
   [Phone] NVARCHAR(4000) NOT NULL,
   [Address] NVARCHAR(4000) NOT NULL,
   [Suburb] NVARCHAR(4000) NOT NULL,
   [Postcode] NVARCHAR(4000) NOT NULL,
   [Number] INT NOT NULL
);
GO
ALTER TABLE [Customers] ADD CONSTRAINT [PK_Customers] PRIMARY KEY ([Id]);
Go
ALTER TABLE [Orders] Add [Customer_Id] INT;
GO

Excepion with 'GO' Keywords

"There was an error parsing the query. [ Token line number = 12,Token line offset = 1,Token in error = GO ]"

Exception without 'GO' Keywords

"There was an error parsing the query. [ Token line number = 12,Token line offset = 1,Token in error = ALTER ]"


Solution

  • SQL Server Compact can only execute a single statement per batch, so you must remove the GO statement, and call ExecuteSqlCommand three times.