Fix LocalDB database structure after converstion from DateTime to int - sql-server

I decided to use int instead of DateTime at this stage. I created a migration with add-migration, but that failed and said I have to run CONVERT command manually. I don't know SQL Server, so I went to the Visual Studio Server Explorer and used the Table design tool to change the values to int and ran Update. It succeeded, however, when I try to save something to my database it throws an error:
System.Data.SqlClient.SqlException: 'Cannot drop database "AppDbContext" because it is currently in use.'
I deleted manually the database files, located in my App_Data folder and rebuilt my app, but same error occurs. When I check the table structure with the design tool, it reflects my changes - the desired column is now int instead of DateTime.
This is the code that accesses the database:
db.Contests.Add(contest);
Contests is indeed the table I changed, but the database structure seems alright. I don't understand why it attempts to drop the database. How can I fix it?

Summary
Always work at Database level when modifying tables - I installed and used SQL Server Managment Studio and changed changed the tables with it successfully.
Error
As per my Cannot drop Database error, it happened, because my DbInitiallizer class was set to drop and re-recreate the database each time the model is changed. I removed that setting and instead configured it to create the database only if it does not exist. Afterwards all I needed to do was run the migration, to notify EF that all the table is now modified to reflect my models and it worked.
Simple steps to change table column property:
Make the desired model changes.
Use SQL Server Management Studio or similar database-level tool to modify the table column
Run add-migration <Name> and update-database in Package manager console tool in Visual studio
Done :)

Related

How to create database using Database Project in Visual Studio if doesn't exists?

I have a Database project for my personal project and I am trying to deploy my code to my DEV server. I frequently delete and re-create my DEV Server. Right now, DEV Server is newly created with SQL Server. Every time I want to deploy my code I have to manually create Database Project and then publish database project. I want to automate creation of Database with database project deployment.
Right now, I have a script that creates database, but I have to execute it manually. And this is working perfectly but I want to automate this step as well.
Is this even possible? If yes, then how? Please explain step by step. Also what will we mention for Initial Catalog in connection string?
Edit:
I tried to create Database by using
CREATE DATABASE LocalDbTest
in Pre-Deployment Script. But it didn't work. It is creating Database, but then tables are not getting created tables under it. Since I used master database as default database, it is creating table under master. It is not letting me select LocalDbTest database as default because it is not yet created, so I have to select Master as my default database. I tried to Change Database by:
USE LocalDbTest
GO
I used it just after creating Database but this didn't work because when generating script it is changing back to default database. This part is coming automatically when generating script.
USE [$(DatabaseName)];
GO
Also Visual Studio is not letting me add database name in front of table name like:
CREATE TABLE [LocalDbTest].[dbo].[TestTable]
I am getting error:
When you create an object of this type in a database project, the object's name must contain no more than two parts.
If you have a script ready for database creation, you can use the Pre-build event to call SQLCMD and run your script.
Edit:
If you have trouble pointing to a database that does not exist, you may have to manually edit the publish profile (ex. dev.publish.xml) and set the TargetDatabaseName element explicitly. You can also set CreateNewDatabase element to True if you want to be recreated every time it gets published.
Answer:
You can use a publish profile and hardcode the target database in it.

Publish of Database Project fails because deployment script attempts to drop and re-create an unmodified table

I'm using Visual Studio 15.8.5 with Sql Server Data Tools 15.1.
I've created an SQL Server database project and imported the schema of an already existing database. I've made several minor changes to a few tables of the database and published the updates to the development database without any problems.
After adding a few SQL scripts to the project, all of them with:
Build Action = None
publish fails, despite no changes have been made in any of the database objects of the project.
This is the part of the auto-generated publish script that causes the problem:
/*
The table [lut].[KAE] is being dropped and re-created since all
non-computed columns within the table have been redefined.
*/
IF EXISTS (select top 1 1 from [lut].[KAE])
RAISERROR (N'Rows were detected. The schema update is terminating
because data loss might occur.', 16, 127) WITH NOWAIT
GO
Table [lut].[KAE] has not been changed, though. One of the scripts is redefining its schema but this should make no difference since this is a 'No Build' script.
What am I possibly doing wrong here?
Edit:
I've done a schema comparison as #MadBert advised. I originally used my actual database as source and my sql server visual studio project as target. No differences were found.
I then switched source and target databases and compared again. The following 'difference' was detected.
As you can see this is not an actual difference, it looks like a Visual Studio bug in schema comparison. Any ideas on how I could circumvent this behavior?
It turned out that a refactor log file was the culprit.
I tried to publish to an empty database, as #Ogglas wisely advised. I noticed that during publish I was getting the following message:
The following operation was generated from a refactoring log file
8e659d92-10bb-4ce9-xxxx-xxxxxxxxx Rename [lut].[KAE].[xxxxx] to
$$$$$$$$$ Caution: Changing any part of an object name could
break scripts and stored procedures.
I then noticed that my SQL Server Database project contained a .refactorlog file
It seems that this log file was generated after I changed the offending table schema. The schema of the table was later reverted to its original state but the log file remained.
I deleted this log file and after that publish finally succeeded!
Had a similar problem when a SQL Server Database project was set to the wrong Target platform. Edit this in project properties to match the target server. Initiate a schema compare again by right clicking on the project and select Schema Compare....
Also check if Ignore whitespace is marked in Schema Compare Options. If you still have a difference one way or another try pasting the text in Notepad++ with Show All Characters on and see if you can spot a difference.
If you still can't find any difference, try creating a new database from the project and use SSMS GUI to compare. Does the table have the same Lock Escalation settings etc?

Troubleshooting the Re Creation of ReportServerTempDB

RESOLVED SEE EDITS:
Like a total noob I deleted our ReportServerTempDB by accident (I have a backup of ReportServer but not ReportServerTemp, live and learn). (Using SQL Server 2008 R2)
To recreate the database I followed several online guides that gave the several steps:
created a new database with the name ReportServerTempDB, and with the same collation as ReportServer (collation was key)
made a new Database Role called RSExecRole with same users as my ReportServer (also key to make sure this role has the correct permissions to the tables)
ran the CatalogTempDB script which ran without a hitch (the version of CatalogTempDB was not sufficient to recreate all of the objects necessary)
Used Reporting Services Config Manager to Change Database and picked ReportServer
Just for good measure turned off and on the SQL Server Reporting Services a few times
But I am still getting an error when I try to load my Reporting Services Home page:
An error occurred within the report server database. This may be due to a connection failure, timeout or low disk condition within the database. (rsReportServerDatabaseError) For more information about this error navigate to the report server on the local server machine, or enable remote errors
What am I forgetting? As an alternative can I simply "create a new report server database" and import a back-up of my original ReportServer? TIA
EDIT: I reviewed the RSExecRole and made sure that it had permission to edit tables and execute stored procedures (online sources did not spell this out very clearly) and after restarting the Reporting Services my error has changed to "An error occurred within the report server database. This may be due to a... Invalid object name 'ReportServerTempDB.dbo.TempCatalog'. Could not use view or function 'ExtendedCatalog' because of binding errors. "
Further reading is suggesting that the name of the temp Report Server is hardcoded into many stored procedures in ReportServer, but my new temp report server has the same name: ReportServerTempDB. Where is the disconnect?
EDIT2: So the script I used, CatalogTempDB, did not create all of the tables necessary to rebuild my temporary Report Server db. I created a new Report Server and ReportServerTempDB (which an altered name) and compared the object in my ReportServerTempDB built using CatalogTempDB to the one the SQL wizard created. Then used the import wizard to add in the missing tables and re-started the Report Service with my original. Voila.
Happy to provide more details about any of these steps.
To recreate the database I followed several online guides that gave the several steps:
created a new database with the name ReportServerTempDB, and with the same collation as ReportServer (collation was key and you need to assign it when yout are creating the db)
made a new Database Role called RSExecRole with same users as my ReportServer (also key to make sure this role has the correct permissions to the tables and stored procedures)
ran the CatalogTempDB script which ran without a hitch (the version of CatalogTempDB was not sufficient to recreate all of the objects necessary, several tables were missing)
To replace the missing tables I created a second ReportServer instance (using Reporting Services Configuration Manager)and compared the temporary db to my re-built temporary db and filled in the holes
Moral of the story: Keep a back up of BOTH ReportServer and ReportServerTempDB

Can I use backup/restore to move a database created with EF Code First?

I have an application that uses EF Code First against a SQL Server 2012 database. I'm using the DropCreateDatabaseIfModelChanges initializer.
I have a database on my development machine that I want to move over to my testing machine, and to do that I'm attempting to use backup/restore. Unfortunately, having done that, I get the dreaded "Model compatibility cannot be checked because the database does not contain model metadata" error.
I don't understand why this is the case - the database works OK on my dev machine. Is it not possible to transfer the database to another machine?
Solved: the issue was that the __MigrationHistory table, while present, was not accessible to the application because of insufficient database privileges. I (temporarily) made the user a DBO on the database, and it all worked fine. (Hat tip to Jayantha).
Now the metadata table is removed from the code first DB and added the __MigrationHistory table to system tables. You can try running Enable-Migrations command in Package Manager Console. Here is more details .

How can I use a SQL Scripts in a Database Project with the System.Data.SQLite data provider?

I've got a project where I'm attempting to use SQLite via System.Data.SQLite. In my attempts to keep the database under version-control, I went ahead and created a Database Project in my VS2008. Sounds fine, right?
I created my first table create script and tried to run it using right-click->Run on the script and I get this error message:
This operation is not supported for the provider or data source you are using.
Does anyone know if there's an automatic way to use scripts that are part of database project against SQLite databases referenced by the databases, using the provider supplied by the System.Data.SQLite install?
I've tried every variation I can think of in an attempt to get the script to run using the default Run or Run On... commands. Here's the script in it's most verbose and probably incorrect form:
USE Characters
GO
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'U' AND name = 'Skills')
BEGIN
DROP Table Skills
END
GO
CREATE TABLE Skills
(
SkillID INTEGER PRIMARY KEY AUTOINCREMENT,
SkillName TEXT,
Description TEXT
)
GO
Please note, this is my first attempt at using a Database, and also the first time I've ever touched SQLite. In my attempts to get it to run, I've stripped any and everything out except for the CREATE TABLE command.
UPDATE: Ok, so as Robert Harvey points out below, this looks like an SQL Server stored procedure. I went into the Server Explorer and used my connection (from the Database project) to get do what he suggested regarding creating a table. I can generate SQL from to create the table and it comes out like thus:
CREATE TABLE [Skills] (
[SkillID] integer PRIMARY KEY NOT NULL,
[SkillName] text NOT NULL,
[Description] text NOT NULL
);
I can easily copy this and add it to the project (or add it to another project that handles the rest of my data-access), but is there anyway to automate this on build? I suppose, since SQLite is a single-file in this case that I could also keep the built database under version-control as well.
Thoughts? Best practices for this instance?
UPDATE: I'm thinking that, since I plan on using Fluent NHibernate, I may just use it's auto-persistence model to keep my database up-to-snuff and effectively in source control. Thoughts? Pitfalls? I think I'll have to keep initial population inserts in source-control separately, but it should work.
I built my database using an SQLite SQL script and then fed that into the sqlite3.exe console program like this.
c:\sqlite3.exe mydatabase.db < FileContainingSQLiteSQLCommands
John
Well, your script looks like a SQL Server stored procedure. SQLite most likely doesn't support this, because
It doesn't support stored procedures, and
It doesn't understand SQL Server T-SQL
SQL is actually a pseudo-standard. It differs between vendors and sometimes even between different versions of a product within the same vendor.
That said, I don't see any reason why you can't run any (SQLite compatible) SQL statement against the SQLite database by opening up connection and command objects, just like you would with SQL Server.
Since, however, you are new to databases and SQLite, here is how you should start. I assume you already have SQLite installed
Create a new Windows Application in Visual Studio 2008. The database application will be of no use to you.
Open the Server Explorer by pulling down the View menu and selecting Server Explorer.
Create a new connection by right-clicking on the Data Connections node in Server Explorer and clicking on Add New Connection...
Click the Change button
Select the SQLite provider
Give your database a file name.
Click OK.
A new Data Connection should appear in the Server Explorer. You can create your first table by right-clicking on the Tables node and selecting Add New Table.

Resources