How to handle EF code-first migrations from my local machine when deploying to Azure? - entity-framework

I finally figured out how to get web.config transformations working, so that locally I have one connection (the one in my default web.config), and then when I publish to Azure, the "debug" transformation is applied so that an Azure-SQL database connection string is used.
That much is working, but now I'm running into a problem with database migrations.
In my Configuration:
protected override void Seed(MG.Context.MentorContext context)
{
System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<MentorContext, Configuration>());
if (!WebSecurity.Initialized)
WebSecurity.InitializeDatabaseConnection("DefaultConnection",
"User", "UserId", "Username", autoCreateTables: true);
}
Now, when I'm running locally and want to update my local database, I open up Package Manager Console and type in 'update-database' and everything works wonderfully.
Sometimes I want to update the remote Azure-SQL database though - so in the past I've done this:
Update-Database -ConnectionString "azure connection string here" -verbose
which was working when I was manually updating my local web.config. Now that I'm using the above transformations, even though I specify a connectionString, DefaultConnection in my Seed method resolves to the un-transformed connection string (my local db), so the Membership tables never get created on the Azure database.
This can be solved by manually updating the default web.config, but that defeats the purpose of using these transformations.
How can I have these transformations applied so that the Seed method of my EF migrations uses the Azure connection strings - OR - how can I tell update-database to use the azure connection string?
I'm trying to avoid manually swapping the connection strings if I can.

You mention a Web.config and "publishing" to Azure; are you using Azure Web Sites?
If so, look at this article. In short, if you configure a connection string on the K/V store of Azure Web Sites with the same name as your connection string, the value you set on Azure will automatically take precedence:
Connection strings work in a similar fashion, with a small additional
requirement. Remember from earlier that there is a connection string
called “example-config_db” that has been associated with the website.
If the website’s web.config file references the same connection string
in the configuration section, then Windows Azure
Web Sites will automatically update the connection string at runtime
using the value shown in the portal.
This should ensure that you Seed method attempts to connect to the right database.

Related

Azure database works on localhost, but not when used with azure service app

So I've been trying to publish my first project to azure. I've got everything set-up, a service app and a sql database.
My initial page loads properly(It's the standard view for a .net core web application).
The first thing I need to do is register a new user. Whenever I try through my azure app (myapp.azurewebsites.net) it fails and the logs says it's db related.
However I try the same thing by running the application on my machine in production environment, again connected to the azure sql server and everything works perfectly. I can register users, I can create posts, I can edit them. The allow access to azure services option is turned on. This error is from the eventlogs. I have not included the stacktrace.
Category: Microsoft.EntityFrameworkCore.Query EventId: 10100 RequestId: 800001be-0000-ba00-b63f-
84710c7967bb RequestPath: /Identity/Account/Register SpanId: |1e5a93ae-43f424904f38ea9f. TraceId:
1e5a93ae-43f424904f38ea9f ParentId: ActionId: c3430236-e61c-4785-a3c3-4f60ba115b6e ActionName:
/Account/Register An exception occurred while iterating over the results of a query for context type
'MyApp.Data.ApplicationDbContext'. Microsoft.Data.SqlClient.SqlException (0x80131904): Server
name cannot be determined. It must appear as the first segment of the server's dns name
(servername.database.windows.net). Some libraries do not send the server name, in which case the
server name must be included as part of the user name (username#servername). In addition, if both
formats are used, the server names must match.
Those are the different ways I tried to add the connection string to the appsettings.json file. (Server name, catalog, user and password have been replaced, they are written correctly in the appsettings file)
Server=tcp:servername.database.windows.net,1433;Initial Catalog=db;Persist Security Info=False;
User ID=user#server;Password=mypassword;
MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
Server=tcp:servername.database.windows.net,1433;Initial Catalog=db;Persist Security Info=False;
User ID=user;Password=mypassword;
MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
Data Source=tcp:server.database.windows.net,1433;
Initial Catalog=db;User Id=#server.database.windows.net;Password=password;
Alright so after a day and a half, I finally managed to fix it. The solution is rather simple and it is most likely my newbie mistake, that caused so much trouble.
I was following a tutorial for setting up the application and database connection after that. In the tutorial, the connection string that was being used, was the default one, found in the "myApp -> Configuration -> Connection strings", the format was:
Data Source=tcp:server.database.windows.net,1433;
Initial Catalog=db;User Id=#server.database.windows.net;Password=password;
This one was working in the guide, but not for me. So what I did, was go to my "sqldb -> connection strings" and copied the one provided there. I then went back to the app configuration and added it as a new configuration string using SqlServer as the Type.
This string was in the format:
Server=tcp:servername.database.windows.net,1433;Initial Catalog=db;Persist Security Info=False;
User ID=user;Password=mypassword;
MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
After that, the app started working properly.

SQL Azure EF Database First Connection String in Azure Management Portal

I have a site running n Azure, which uses EF Database First model.
If I embed the connection string in the web.config and deploy all is rosy.
<add name="MyEntities" connectionString="metadata=res://*/App_Code.Model.csdl|res://*/App_Code.Model.ssdl|res://*/App_Code.Model.msl;provider=System.Data.SqlClient;provider connection string='Data Source=my.database.windows.net;Initial Catalog=myTest_DB;User ID=***;Password=***; MultipleActiveResultSets=False'" providerName="System.Data.EntityClient"/>
But, I don't want the connection string in the web.config because it contains credentials.
So I moved it to the connection string area in Azure Properties.
First issue I hit is getting metadata invalid keyword error.
I solved that by changing the type from SQL Database to Custom.
However, I now get this error:
The connection string 'MyEntities' in the application's configuration
file does not contain the required providerName attribute."
I've trawled the web and tried many variations of the connection string but not yet found the correct one.
Note: I guess I could make this an app setting and move the initialisation of the string to code, but even if only for curiosity sake I would like to know how to do it via the portal.
The problem is not the connection string, but the inability to specify the providerName from the portal.
Try publishing with a local or dummy connection string in place, and overwriting it as you have in the Azure Application Settings. See this answer: https://stackoverflow.com/a/18964294/94853

Failing to get EF connection string to work when setup in Azure's management portal?

I am using ASP.NET MVC4 deployed on WebApps, EF6, Azure SQL Database
I have two connectionstrings, one direct to the DB and one that is needed as I am using Entity Framework. If I setup the first via Azure and leave the EF string in web.config, all works fine. Once I try to move the EF connectionstring to Azure, it breaks.
I have tried to follow all the posts on how to setup an EF connection string in Azure Management Portal, and the advice seems to be to use the following:
In Management Portal:
Name:
EFConnectionString
Value:
metadata=res://MyModel/model.csdl|res://MyModel/model.ssdl|res://MyModel/model.msl;provider=System.Data.SqlClient;provider connection string="Data Source=tcp:myserver.database.windows.net,1234;Initial Catalog=mydatabase;User ID=Admin#myserver.database.windows.net;Password=12345678"
SQL Database:
Custom
Note:
" is replaced by " in the Azure string.
In Web.config I still need the following:
<add name="EFConnectionString" connectionString="" providerName="System.Data.EntityClient"/>
I have changed certain details in the connectionstring for security reasons, but the true string does work fine in Web.config.
However when I do attempt the above, I get :
The page cannot be displayed because an internal server error has occurred.
Further Log error message:
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
Any help appreciated. I am trying to do this to enhance the security of stored passwords for accessing DB on Azures, as I understand that setting them up via the portal encrypts them.
Thanks.
First check your deployment. I've run in a similar problem, and after a couple of hours struggling I found out that I was deploying without actually sending connection strings, falling back to whatever was in the portal config... the others keys in the we.config were being sent over, but the conn strings weren't... after I properly set it up on the portal, everything went back to normal...

EF Code first migrations not running after deploy to Azure

I have two folders for my migrations (AuthContext and UserProfileContext), each has their own migration and some custom sql to run afterwards for data migrations and whatnot.
This works fine when using package manager console. I
Restore from production
Run Update-Database -ConfigurationTypeName Migrations.Auth.Configuration
Run Update-Database -ConfigurationTypeName Migrations.UserProfile.Configuration
Then everything is very happy in the new database, migrations executed data shuffled where it needs to.
I tried to test out the migrations on publish piece by:
Restore production on dev database
Single connection string (all contexts use the same) pointed to dev database
Publish to azure web site
Checked the box for Apply Code First Migrations
Selected that single connection string
Okay it published fine; however, when I went to look at the database, nothing happened! It did not create the necessary tables, columns, or data moves.
TLDR; Code first migrations are not running after publish to Azure
Update 1
I've tried any combination of the below: only one single connection string so I'm guessing that's not the issue, and execute migrations is checked.
On publish the api runs but no database changes are made. I thought perhaps I needed to hit it first but I just get random errors when I try to use the api (which now of course relies on the new database setup), and the database is still not changed.
I've seen a couple references out there about needing to add something to my Startup class but I'm not sure how to proceed.
Update 2
I solved one issue by added "Persist Security Info=True" to my connection string. Now it actually connects to the database and calls my API; however, no migrations are running.
I attached debugger to Azure dev environment and stepped through... on my first database call it steps into the Configuration class for the Migration in question, then barfs and I can't track down the error.
public Configuration()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = #"Migrations\Auth";
ContextKey = "AuthContext";
}
Update 3
Okay, dug down and the first time it hits the database we're erroring. Yes this makes sense since the model has changed, but I have migrations in place, enabled, and checked! Again, it works fine when running "Update-Database" from package manager console, but not when using Execute Code First Migrations during publish to Azure
The model backing the 'AuthContext' context has changed since the
database was created. Consider using Code First Migrations to update
the database (http://go.microsoft.com/fwlink/?LinkId=238269).
Update 4
Okay I found the root issue here. VS is setting up the additional web.config attrib for databaseInitializer on only one of my database contexts, the one not mentioned is in fact hit first from my app.
So now I have to figure out how to get it to include multiple contexts, or, combine all of my stuff into a single context.
The answer to this post is not very detailed.
This article explains what I had to do to fix a similar problem to this:
https://blogs.msdn.microsoft.com/webdev/2014/04/08/ef-code-first-migrations-deployment-to-an-azure-cloud-service/
I'll roughly describe the steps I had to take below:
Step 1
Add your connection strings to your dbContexts, in my situation, they were both the same.
Step 2
Add this to your web.config
<appSettings>
<add key="MigrateDatabaseToLatestVersion" value="true"/>
</appSettings>
Step 3
And add this to the bottom of your global.asax.cs / Startup.cs(OWIN startup)
var configuration = new Migrations.Configuration();
var migrator = new DbMigrator(configuration);
migrator.Update();
Solved! To summarize the solution for posterity:
Enable Code First Migrations only enables them for one base connection string per checkbox checked, regardless of how many contexts have migrations against that base connection string. So in my case I broke out the two in question into two different connection strings.
Then I was hitting other errors and identified that if you're changing the base connection string to the model backing asp identity you need to include (one time publish) the additional flag base("AuthContext" , throwIfV1Schema: false)
For anyone who has this issue and may have overlooked the following: be sure to check that you have correctly set the connection string in your Web.config file and/or Application settings on Azure. This includes DefaultConnection and DefaultConnection_DatabasePublish.
In our case the former was correct but the latter contained the wrong database instance because it had been carried over from an App Service clone operation. Therefore the wrong database was being migrated.

EF5 connection string error only in production

When on my dev machine, all works perfectly. Even using production connection values (so even when I connect to production from the dev machine). I don't think it's a permission problem because I am using the same credentials, just using EF5 instead of linq2sql, as the previous version of the service that worked. Also, the sql-profiler does not show a failed login attempt.
Connection string is:
Data Source=MYSQLSERVER;Database=MYDB;Integrated Security=True;
The error is:
Invalid value for key 'attachdbfilename'.
I have logged the connection string being passed into the dbContext code:
Database.Connection.ConnectionString = settings.DbConnectionHourly;
This is a class that inherits from my real dbContext (which packaged in a dll) and the settings get injected. Again, this works in Dev but not in production (server 2008 r2, IIS 7.5, framework.4).
Turns out that entity framework was trying to be very smart, but it was giving a very un-smart error message. So by convention, if you don't pass the context name in as a constructor, entity framework will assume the classname as the name of the connection string. What it will also do (which I was unaware of), is in development it will automatically connect to and create a schema using the visual studio built in sqlExpress. So in development, everything worked because this 'automagic' creation succeeded and since I later changed the connection to a different database, I was none the wiser about what EF was doing under the covers (EF was doing the wrong things but the end result worked).
However, when the application went to production, there is no sqlexpress or any database on the webserver so the automagic connection/creation sequence failed. Now if the error message had any useful information in it, this would be obvious. But since I had never set an 'attachdbfilename', nor did it tell me what the value of 'attachdbfilename' was or any context or what it was trying to do, this made figuring this out that much more challenging.
The fix was simple:
public HourlyContext(ISettingsWrapper settings)
: base(settings.DbConnectionHourly)
{ }
Instead of setting the connection after the context gets created (the creation process will immediately try to work it's magic with it's built in conventions/defaults), I now set it immediately through the constructor.