Different user for migrations - .net-core

I'm trying to run
dotnet ef database update
When I do so, I get an error about not being allowed to CREATE TABLE. Not entirely surprising as I don't want the user I have the website running under to be able to create tables. So, after a bit of searching I found a solution that basically created an inherited context, and with that context used a different set of credentials. So, I tried;
dotnet ef database update --context ScaffoldContext
And I got the same error. I checked my connection string, yes, it's a user I can use to create a table with. Confirmed through SQL CLI. So, I added CREATE TABLE privileges to my site user, and the error changed. Suggesting that the base connection string was the one that mattered and it's ignoring using my elevated user. I tried moving the configuration into the OnConfiguring override in my inherited scaffold context, instead of services.AddDbContext in my Startup.cs. However, looking this up it looks like the wrong way to go about that. When I added CREATE TABLE privilege to my site user, I got a different exception about not being allowed to touch dbo.
This is driving me nuts, I don't want to use my site user as my migration user and it seems every example I find is from older versions of EF or dotnet core. Does anybody have any solid guides on how to go about managing users correctly using migrations with 2.1?
Note: If I change my connection string to be my sa user, it works fine. So the migration will go through. I'm just not wanting to give either full privileges to my site user or swapping credentials around in connection strings every time I need to run a migration.

Related

Implement custom ASP.NET Identity using existing database

I would like to customize ASP.NET Identity to work with an external database.
The default schema looks like that:
The part that bothers me, is the User table.
I succeeded to move the database to SQL Server Express and then I tried to modify the Table and deleted some columns.
When I tried to build and run the project I got multiple errors demanding for the columns I deleted and there is no mention to them in the code (Just new MVC project).
I would like that it will look more like this:
Of course I'll want to add some more table but that we'll be after the Users part will be complete.
So, is there some kind of tutorial that can explain how to customize Identity to my needs ?
Or anything help that can help me build stable users system.

Schema not updating when publish web app from Visual Studio

I am building an ASP.NET MVC EF app with code-first migrations and hosting it in Azure with Azure SQL DB. The first time I published this, it went fine. But since then my models changed, and my schema in the Azure DB is not getting updated to match. When I deploy, I do have "Execute Code First Migrations" checked. When that wouldn't work, I deleted my DB and then recreated it in the Azure portal, figuring that would trigger it getting updated. But then that didn't work, so I set AutomaticMigrationsEnabled = True in the migration Configuration. It is STILL not working, so currently my DB in Azure has none of my tables. HOW can I get the DB in Azure to be forced to update to match my models so the published site will work?? I did try looking for if there's a way to script the VS local DB to a Create query and execute that in SQL management studio, but couldn't find how to do that.
If you have made sure that you have selected update database in the publish setting, and the connection string is correctc and its still not updating. Maybe the following will help for you:
I sometimes get an issue like this, it is quite frustrating, My publish file is correct and my settings are set to allow SQL updates to occur during publishing. But sometimes the database hasn't been updated and I get a nice "backing context has changed" error, sometimes the culprit is the migration table that hasn't been updated. Unfortunately the only sure way to get your databases in sync is to check what migration history they are both at, by comparing [dbo].[__MigrationHistory]
If your published server is missing the latest migration history, then you can generate an SQL script of that by typing into the package manager console:
Update-Database -Script -TargetMigration [migration name]
'migration name' should be the name of the last migration that your published server had, visual studio will generate sql script that can be used to bring the database up to the latest migration from that target migration.
Sometimes (though very rarely, its only happened once or twice for me) the above doesn't work for whatever reason (usually because migration files have been deleted), if that is the case then its a good idea to script the whole database, and cherry pick the sql you need from that.
Update-Database -Script -SourceMigration:0
This will generate a script for every migration, you can then cherry pick based on the changes you've made. The 'latest' changes will be closer to the bottom of the file. every migrational change will start with an if check:
IF #CurrentMigration < '201710160826338_mymigration'
BEGIN
You can use this to pick the bits that you need, if you do pick the SQL be sure to include the update to the migration history. It will be at the end of the if block and look something like this:
INSERT [dbo].[__MigrationHistory]([MigrationId], [ContextKey], [Model], [ProductVersion])
VALUES (N'201710101645265_test', N'API.Core.Configuration', 'Some long checksum')
Including the migration history will ensure that visual studio doesn't have the problem again.
Hope this helps.

Code First and Existing Database with Data

I'm developing a windows application which uses SQL Server Database. I have different versions of this application and they have different database structure, so I need to migrate database to the latest version on application start. I want to compare the database structure with the application model, then do alter, create or drop commands.
Also I want to use EF Code-First ORM, after some search I've figured it out that there are some useful commands and configs in code first. But the problem is, as I know, all of them drop the existing database and create a new one so the data will be lost while I need the data.
I used these lines in my application start function:
var migrator = new DbMigrator(new Configuration());
migrator.Update();
But after execution this line I will get this exception:
There is already an object named 'SomeTable' in the database.
I know that, it's right and there is that table but in structure is changed! How can I compare the structure and do the rest?
That's not how migrations work. You need a migration for every version of your database so EF can check the __MigrationHistory table and see if it has been applied. If your initializer is set to MigrateDatabaseToLatestVersion your database won't be recreated on model changes.
You could try to recreate the history: roll back to your oldest database, add a migration, add 2nd oldest version changes, create a 2nd migration, etc.
Another option is to add a migration for where you are now, generate a script (update-database -Script) then comment out the stuff that exists in each deployed database before applying it.
Yet another option would be to use the VS Schema compare utility against each database and your current database to get the changes over. Then apply a baseline migration to each (add-migration Initial -IgnoreChanges).
Now moving forward you can generate a series of migrations and your code should work as expected.

How to work with LocalDB and EF, without using migrations

I am on VS 2012 RTM, with EF 5. I am doing Code First, but trying to ignore Code Migrations since I am just in development. To avoid them, I have this set
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SomeContext>());
Occasionally, even when I don't think I've touched the model, it decides to recreate. That's fine. But it usually results in the error
Cannot drop database because it is currently in use.
So I decided to delete the database entirely. I go into VS, go to the "SQL Server Object Explorer", find the DB and delete it. Now I'm stuck at
Cannot attach the file '{0}' as database '{1}'
I had this happen last night and I just fiddled around until it work (shut down tasks, restart VS, changed the DB and file names in the web.config, etc.
So question 1) How do I get out of this state?
But the more important question, how do I prevent myself from getting in this state at all?
The SQL Server Object Explorer window can hold a connection to the database. Closing the window and all windows opened from it releases the connection.
I had the same problem and managed to fix it. The main problem is that EF won't automatically create the database. The solution is not very hard.
First, go to the Solution Explorer and manually create the database. To do this, go to the folder where your database is located (usually App_Data). Right-click on this folder and click on Add -> New Item. Select the Data tab and select SQL Server Database. Make sure you enter the name Entity Framework expects (which is specified in the Cannot attach the file '{0}' as database '{1}' error message).
Then most likely you will get an error message that says that the database does not contain any model metadata. To circumvent this, change your database initialisation to:
Database.SetInitializer(new DropCreateDatabaseAlways<SomeContext>());
Now run the application and the database should be there with tables correctly created. Once this step has been successfully executed, you change change your database initializer back to:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SomeContext>());

Creating Membership DB (ASPNETDB) on remote server?

I'm building a web application which soon I'll be promoting to production. This application has a login screen, as you know I used the integrated DB for developing. Now I want to move this database to a full SQL Server 2005. I'm using the aspnet_regsql.exe to create my membership tables and stored procedures in the SQL Server 2005 but I'm getting an error:
An error occurred during the execution of the SQL file 'InstallMembership.sql'. The SQL error number is 207 and the SqlException message is: Invalid column name 'FailedPasswordAnswerAttemptWindowStart'.
I google this for half of the day already and I can't seem to fine what's wrong, does anybody have ANY ideas on what am I doing wrong here? Any help will be really appreciate it.
The easiest way to deploy a brand new database to a remote server is to just publish the database from within Visual Studio. Once you do that you have the scheme and data all in one script. You then access your server either via a local SQL manager connection or a remote manager and run the script on your remote database.
The site 4GuysFromRolla has a nice little walk through with graphics which describe how to accomplish the publishing of your local database to your hosted one.
Good luck, and hope this helps you out some.
Go through the *.sql script file and see where that column reference is. Then you'll be able to see what exactly the script is doing to cause this error. My guess would be that it is getting caught up on referential integrity. If it is trying to create a foreign key constraint that that table/column does not exist then you'll see that error.
But back to the original question at hand. You don't need to recreate your whole database. That script file is to lay down the Membership for an empty database. If you have a working dev database you can just back it up and restore it to a production instance. No need to rebuild the membership database objects.

Resources