Invalid column name 'CreatedOn' using EntityFramework on Windows Azure - entity-framework

Using ASP.NET MVC, Entity Framework 6 Code First on SQL Express everything runs fine on my local machine. When I publish to Windows Azure things start to fall apart. The default MVC page displays just fine. And I think the data is correct because I can compare the Azure database with my local SQL Express and everything is identical except for a couple records in __MigrationHistory. This is a new app, so I don't think the other SO issues about converting from previous versions of EF apply.
When I try to access a page that queries the database I get the following exception when I attach the Visual Studio debugger to the Azure web site. It fails on the first call to dbContext.SingleOrDefault. Note that I can see the full data of the dbContext in the debugger when it pauses.
System.Data.SqlClient.SqlException occurred
_HResult=-2146232060
_message=Invalid column name 'CreatedOn'.
HResult=-2146232060
IsTransient=false
Message=Invalid column name 'CreatedOn'.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
_doNotReconnect=false
Class=16
LineNumber=2
Number=207
Procedure=""
Server=tcp:*.database.windows.net,1433
State=1
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
InnerException:
Any help would be much appreciated.

Seems like this is something to do with Migrations and the removal of the CreatedOn column.
I get this exception using the MiniProfiler. I deleted the pdb files from the bin folder (as suggested in a post in the MiniProfiler github site) and it no longer happens.
You might want to check references to EF as it could be a reference in a [nuget] package built against an earlier version of EF.

Related

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.

Can I access a migrated EF database with "old" code?

If I have an EF6 Code First environment in need of a schema change, is it possible to configure it in such a way that I can apply the migration (via Update-Database -Script) before the code gets deployed?
I just ran a simple test with a console app building a DB with migration "Initial", taking a copy of the application at this point. I then modified the schema by adding a new property to my entity and added a "V2" migration and ran Update-Database. When trying to run the "old" code against this migrated DB, I get an InvalidOperationException "The model backing the context has changed since the database was created."
Is the Continuous Delivery type operation where you might want one server running new application code with others running old versions possible with EF code first?
can you modify old code ?
if yes disabling schema checking in old code is an option.
btw: Are you sure the added column is nullable or as a default value ?
to avoid surprises, you can also use a connection string that has read only rights on the schema to avoid data corruption.

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.

Querying Ef context using LinqPad: Argument Exception

I have added Ef connection in linqpad like following
As you can see connection is successfully added but when i want to query against this connection i get the following exception
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
it seems to be connected with connection string but how it would be solved, i have no idea. The context is defined in asp.net mvc project (no separate project for data access) and connection string is in web.Config file as usual
I had this same problem, I was able to solve it by following the instructions here
1) Find the path that LINQPad uses for its configuration file by excuting this: AppDomain.CurrentDomain.SetupInformation.ConfigurationFile.Dump()
This returned for me the following: C:\Program Files\LINQPad4\LINQPad.config
I was suprised this returned LINQPad.config instead of LINQPad.exe.config
which is what you would typically expect since most .NET applications name the > file the same as the executable.
Take your App.config and copy it to the location above naming the config
file whatever yours returned. In my case it was LINQPad.config
Close LINQPad or the TAB that you have opened to execute your assembly and reopen to get LINQPad to read the configuration file.
http://coding.infoconex.com/post/2012/06/01/Getting-LINQPad-to-read-your-applications-AppConfig-settings.aspx
Recent versions of LINQPad support direct connections to projects with a DbContext or ObjectContext. With that connection type, you can specify your app.config / web.config when setting up the connection.
http://www.kevinlabranche.com/blog/ConnectingLinqPadToEntityFrameworkCodeFirst.aspx

Is the Entity Framework compatible with SQL Azure?

I cannot get the Entity Framework to work against SQL Azure. Is this just me or is it not intended to be compatible? (I have tried the original release of EF with VS2008 as well as the more recent VS2010 Beta 2 version)
To check this I created the simplest scenario possible. Add a single table to a local SQL Server 2008 instance. The table has two columns, a primary key of type integer and a string column. I add a single row to the table with values of (1, foobar). I then added exactly the same setup to my SQL Azure database.
Created a console application and generated an EF model from the local database. Run the application and all is good, the single row can be returned from a trivial query. Update the connection string to connect to the SQL Azure and now it fails. It connects to the SQL Azure database without problems but the query fails on processing the result.
I tracked the initial problem down using the exception information. The conceptual model had the attribute Schema="dbo" set for the entity set of my single defined entity. I removed this attribute and now it fails with another error...
"Invalid object name 'testModelStoreContainer.Test'."
Where 'Test' is of course the name of the entity I have defined and so it looks like it's trying to create the entity from the returned result. But for some unknown reason cannot work out this trivial scenario.
So either I am making a really fundamental error or SQL Azure is not compatible with the EF? And that seems just crazy to me. I want to use the EF in my WebRole and then RIA Services to the Silverlight client end.
While I haven't done this myself I'm pretty sure that members on the EF team have, as has Kevin Hoffman.
So it is probably just that you went astray with one step in your porting process.
It sounds like you tried to update the EDMX (XML) by hand, from one that works against a local database.
If you do this most of the changes will be required in the StorageModel element in the EDMX (aka SSDL). But it sounds like you've been making changes in the ConceptualModel (aka CSDL) element.
My guess is you simply need to replace all references to the dbo schema in the SSDL with whatever schema is the SQL Azure schema.
Hope this helps
Alex
To answer the main question - Yes, at least the Entity Framework v4 can be used with SQL Azure - I haven't honestly tried with the initial version (from the .Net Framework 3.5. SP 1).
A little while back I did a complete project and blogged about the experience: http://www.sanderstechnology.com/?p=9961 Hopefully this might help a little bit!
Microsoft's Windows Azure documentation contains How to: Connect to Windows Azure SQL Database Using the ADO.NET Entity Framework.
After creating your model, these instructions describe how to use SQL Azure with the Entity Framework:
Migrate the School database to SQL Database by following the instructions in How to: Migrate a Database by Using the Generate Scripts Wizard (Windows Azure SQL Database).
In the SchoolEFApplication project, open the App.Config file. Change the connection string so that it connects to your SQL Database.
<connectionStrings>
<add name="SchoolEntities"
connectionString="metadata=res://*/SchoolDataModel.csdl|res://*/SchoolDataModel.ssdl|res://*/SchoolDataModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=<provideServerName>.database.windows.net;Initial Catalog=School;Integrated Security=False;User ID=<provideUserID>;Password=<providePassword>;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False""
providerName="System.Data.EntityClient"/>
</connectionStrings>
Press F5 to run the application against your SQL Database.