EF5 connection string error only in production - entity-framework

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.

Related

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.

Web app with EF + database first not working on Azure

I have a ASP.NET MVC application which uses EF (v6) as data access layer. My application works fine on IIS Express and also when deployed to the server running IIS 7.5.
The problem is that I'm getting the following exception when I deploy it to Azure (Web Sites).
Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception.
I've searched the web and I made sure my connection string starts with "metadata=" + checked my db context class' constructor to be sure it contains the correct name (in my case it's "name=PsDataEntities"))
My connection string looks like this: <add name="PsDataEntities" connectionString="metadata=res://*/PsDataModel.csdl|res://*/PsDataModel.ssdl|res://*/PsDataModel.msl;
provider=System.Data.SqlClient;
provider connection string="data source=SERVER_NAME;initial catalog=DB_NAME;user id=UID;password=PWD;
MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Anybody had the same problems?
Any help is appreciated
I did a few more tests (like changing metadata in the connection string to use fully qualified names instead of '*') without success, then I decided to set my metadata (regarding .csdl/.ssdl/.msl) programatically with the help from this post. Application now works correctly when deployed to Azure.

Tables not created with Entity Framework on Azure

I am using Entity Framework using Code First and the Fluent API.
When developing on my local machine, the database and tables are created as expected and everything works fine.
When deploying to my Azure web role the database is created, but the tables are never created. If I try a HTTP request touching DbContext, the request times out and finally my web role only returns "Service Unavailable".
The model is large, but not extremely so (43 tables are created on my dev machine).
What can be wrong here? Here is my Azure SQL connection string, where you can see that I set the timeout quite high:
<add name="MyConnectionString" connectionString="Server=tcp:myserveronazure.database.windows.net,1433;Database=MyDatabase;User ID=MyUser#myserveronazure;Password=thepassword;Trusted_Connection=False;Encrypt=True;Connection Timeout=120;PersitSecurityInfo=true;" providerName="System.Data.SqlClient" />
EDIT: After RDP:ing into the Azure VM, I see in the Event Log that w3wp.exe (the IIS worker process, if I'm not mistaken) crashes. The log doesn't list any error message.
Enityframework have three Database Initializer by default CreateDatabaseIfNotExists,DropCreateDatabaseWhenModelChanges and DropCreateDatabaseAlways that are executed when you hit the context for the first time, if you are using migrations (i think is the case) you must use the MigrateDatabaseToLatestVersion initializer to work in the application deployment. Hope it works!

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

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.