When I generate a migration script using the ef 7 powershell commands
dnx ef migrations add Initial -c MyDbContext
dnx ef migrations script -c MyDbContext
I get a script that has, in the first few lines, the following;
Using context 'MyDbContext'.
Generating up script for migration '20151001104737_Initial'.
IF OBJECT_ID(N'__MigrationHistory') IS NULL
CREATE TABLE [__MigrationHistory] (
[MigrationId] nvarchar(150) NOT NULL,
[ProductVersion] nvarchar(32) NOT NULL,
CONSTRAINT [PK_HistoryRow] PRIMARY KEY ([MigrationId])
);
GO
When I run the script on my SQL Databases to apply my migration I get the error
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'MyDbContext'.
Msg 208, Level 16, State 1, Line 98
Invalid object name '__MigrationHistory'.
I have run this script on SQL Server database versions 11, 12 & 13 and I get the same error throughout. It is clearly complaining that the table name __MigrationHistory isnt a valid table name it seems.
Figured out the problem
I was piping the ef command into a file and the first two lines are just descriptions of what is going on while the command is running
so if you are doing something like
dnx ef migrations script -c MyDbContext > myscript.sql
then make sure to remove the first two lines before running the script
Related
I am using EF Core (3.1.15). In a previous migration (also created in 3.1.15), a column was referenced that was dropped later on. The idempotent script does check if the migration was performed on the database (which it is, and the reference still shows in the __EFMigrationsHistory table). However the check doesn't have the expected result and the script due to the inexistent column.
Q: why is the inexistent column tripping the execution of the SQL script?
Script was created with
dotnet-ef migrations script -i -o migrations.sql
Relevant part of the automated script that fails, where ReferenceToLedgerId is the column dropped in later migration:
IF NOT EXISTS(SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20210612052003_CLedger')
BEGIN
UPDATE LedgerTable SET LedgerId = ReferenceToLedgerId
END;
Error:
Msg 207, Level 16, State 1, Line 3
Invalid column name 'ReferenceToLedgerId'
When running the following SQL query, the result comes back as expected:
SELECT *
FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20210612052003_CLedger'
MigrationId
ProductVersion
20210612052003_CLedger
3.1.15
The database is Azure SQL Database. Script doesn't fail on local SQL dev database. A dozen migrations have been applied since then, and only now the script fails.
Below was the call that created the specific script:
migrationBuilder.Sql("UPDATE LedgerTable set LedgerId = ReferenceToLedgerId", true);
I tried to place the table and column names in square brackets, but that made no difference (eg. [ReferenceToLedgerId]. The script fails in Azure DevOps release when using SQLCMD and also fails when using Azure Data Studio, both accessing the Azure SQL Database.
Additional check
I changed the script to do a quick check:
PRINT '#Before IF'
IF NOT EXISTS(SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20210612052003_CLedger')
BEGIN
PRINT '#Within IF'
--UPDATE LedgerTable SET LedgerId = ReferenceToLedgerId
END;
PRINT '#After IF'
To which I get the following result:
Started executing query at Line 1
#Before IF #After IF
Total execution time: 00:00:00.010
If I uncomment the UPDATE statement it fails again. So I can only conclude that the code path works as intended, but that the server still checks for the existence of the column. I am not familiar with SQL to understand why this would be, or why it only fails for this one line while the column itself is referenced in other lines of the SQL script without it failing.
That batch will fail on every version of SQL Server. eg
use tempdb
go
create table __EFMigrationsHistory(MigrationId nvarchar(200))
create table LedgerTable(LedgerId int)
go
insert into __EFMigrationsHistory(MigrationId) values (N'20210612052003_CLedger')
go
IF NOT EXISTS(SELECT * FROM [__EFMigrationsHistory] WHERE [MigrationId] = N'20210612052003_CLedger')
BEGIN
UPDATE LedgerTable SET LedgerId = ReferenceToLedgerId
END;
Fails with
Msg 207, Level 16, State 1, Line 8
Invalid column name 'ReferenceToLedgerId'.
Because the batch cannot be parsed and compiled. It's simply not legal to reference a non-existent table or column in a TSQL batch.
You can work around this by using dynamic SQL, so that the batch referencing the non-existent column is not parsed and compiled unless the migration is being applied.
migrationBuilder.Sql("exec('UPDATE LedgerTable set LedgerId = ReferenceToLedgerId')", true);
This is documented here:
Tip
Use the EXEC function when a statement must be the first or only
one in a SQL batch. It might also be needed to work around parser
errors in idempotent migration scripts that can occur when referenced
columns don't currently exist on a table.
https://learn.microsoft.com/en-us/ef/core/managing-schemas/migrations/operations
Using SQL Server 2016. Have a locally hosted database that uses the Windows login for the sa, which is what I am using to login.
Yesterday I ran
CREATE TABLE [Otis].[AnalyzerGroups]
(
[id] [int] IDENTITY,
[Name] [varchar](50) NULL
);
and got command successfully completed. Today I tried selected from this table but got an error:
Msg 208, Level 16, State 1, Line 1
Invalid object name 'Otis.AnalyzerGroups'
So I thought I misremembered and tried running the create statement again but then got the error -
Msg 15530, Level 16, State 1, Line 1
The object with name "AnalyzerGroups" already exists.
The statement has been terminated.
So then I tried DROP TABLE [Otis].[AnalyzerGroups]; and got
Msg 3701, Level 11, State 5, Line 1
Cannot drop the table 'Otis.AnalyzerGroups', because it does not exist or you do not have permission.
I tried making a new test table and the same thing. The first time I run the create statement command successfully completes, but then I can't select / insert / drop from the table, and I cannot see it in the Object explorer either.
I assume this must be some permissions issue but I don't know what property is keeping me from viewing these tables - its not like I'm putting security on these tables, and I can see every other table in our database. Any thoughts?
You put it most likely in the wrong database. Try this.
sp_MSforeachdb 'SELECT "?" AS DB, * FROM [?].sys.tables WHERE name like
''%AnalyzerGroups%'''
There was a trigger in the SQL Server database that fired any time a new table was created under any schema, and would then transfer it to the dbo schema. So my tables did exist, but they were under the schema I was expecting because of this trigger. Why does this trigger exist? Got me. But it's in production and has been for over a decade so there's some reason/it's definitely not changing. Thanks for the help though everyone.
I created and altered a trigger and everything worked well, but when I started the SQL Server Management Studio later on, the following error appeared:
Msg 2108, Level 15, State 1, Procedure store_110, Line 43
Cannot create trigger on 'IT_ServerDB.dbo.Users' as the target is not in the current database.
Cannot create trigger on 'IT_ServerDB.dbo.Users' as the target is not in the current database.
It seems ,you are using three part naming like below
'IT_ServerDB.dbo.Users
use two part naming
use IT_ServerDB
go
create trigger triggername
on
and rest of syntax
Exclude a post deployment script in Visual studio 2013 SQL Server project. I am not explaining the whole requirement why I have to do this. I am explaining part of my issue; please bear it.
I have the following script:
CREATE SCHEMA [College]
CREATE TABLE [College].[Department]
(
[Name] varchar(50) NOT NULL,
)
In a post deployment script I have a script file which is not included in the build, and I am inserting a value in the department table:
INSERT INTO [College].[Department]
([DeptId], [DeptName])
Values('77ACE81C-7C41-4A31-8F39-9814E36548A1', 'Computer')
As my department table doesn't have Department Id, I want to exclude this script, so based on a condition I am including this file by taking the help of a command-line variable. My post deployment file has the following entry:
IF('$(UseDepartMent)' = 1)
BEGIN
PRINT N'Command Line UseDepartment is 1'
:r .\Script.DepartMentTableEntry.sql
END
GO
(90,1): SQL72014: .NET SqlClient Data Provider: Msg 207, Level 16, State 1, Line 47 Invalid column name 'DeptId'.
I have been trying to get Liquibase's maven plugin to work with a simple SQL Changeset.
It's a slightly modified version of the example at: http://www.liquibase.org/manual/formatted_sql_changelogs
-- liquibase formatted sql
-- changeset nvoxland:1
CREATE TABLE test1 (
id int PRIMARY KEY,
name varchar(255)
);
CREATE TABLE test2 (
id int PRIMARY KEY,
name2 varchar(255)
);
The problem is, it fails with an error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE TABLE test2
If I remove the second create statement, it will succeed.
This happens, when trying to run it with Maven, using the liquibase-plugin. If I run the same changelog file using the command line tool, it will execute without errors.
My liquibase-plugin is of version 1.9.5.0 and liquibase-core is 2.0.5.
The database is MySql 5.5.27 and JDBC Driver is 5.1.24 - I used the same driver with Maven and the command line tool.
The liquibase-plugin is really old (from 2009) and doesn't split the SQL on ;. You should use org.liquibase:liquibase-maven-plugin:2.0.5 instead, which is the current version.