Azure EF Code First Migration Initializer - entity-framework

I am just messing with Azure, and I can't seem to get my Db to work. I am following what it says here: https://www.windowsazure.com/en-us/develop/net/tutorials/web-site-with-sql-database/ and I updated my web.config to have this:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<contexts>
<context type="DownloadThis.Models.DownloadThisDb, DownloadThisDb">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion">
<parameters>
<parameter value="DownloadThisDb_DatabasePublish" />
</parameters>
</databaseInitializer>
</context>
</contexts>
</entityFramework>
As is shown in the example, but I keep getting this error:
Format of the initialization string does not conform to specification
starting at index 0.
I have triple checked my connectionString, so that isn't it - any ideas?

Assuming that you're publishing with the VS2012 publish wizard, I've run into the same issue. If you choose to have the publishing wizard enable code first migrations instead of manually wiring them up in your code, then you need to provide a connection string in the publish settings. Your normal connection string is not used to run the migrations, this new connection string is used for this purpose only. This is nice because you can specify an account that has elevated privileges for performing your migrations, however, your app won't run under this user context. The problem is that the wizard doesn't make the need to specify this connection string very obvious. When you don't supply this, you end up with a null migration connection string and you spend a lot of time trying to figure out what's wrong with your normal connection strings.
Let's say that your context class is named FooContext. By convention, you'll have a connection string in your web.config named FooContext. When you enable code migrations via this wizard, the wizard will create a second connection string named FooContext_DatabasePublish that will only be used for running your code first migrations.
This blog post on MSDN explains this process in some detail.

I think you're missing a . in your type string:
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion">
The red rectangle over the code makes it hard to read...
If that doest fix it, post a comment and I'll work up a sample to match yours and see if I can get it to work...
[UPDATED 2012-08-15]
OK - I think I know what's going on here... You mentioned "I updated my web.config to have this:" and showed your XML. When I ran through the tutorial, I did NOT have to enter ANY extra XML into my web.config. During the publishing process, the XML was added for me automagically by Visual Studio's deployment process and it all "just worked".
Here's your solution:
Go back to the original web.config file without these updates, and try publishing again.
For reference, here are the <entityFramework> sections from my two web.config files, first from my project, second from my hosted service (I got that by connecting to the running site via FTP and downloading it). The VS project is called 11964172 after the SO record number for this post:
local web.config file settings
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
deployed web.config file settings
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<contexts>
<context type="_11963331.Models.ToDoDb, 11963331">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[_11963331.Models.ToDoDb, 11963331], [_11963331.Migrations.Configuration, 11963331]], EntityFramework, PublicKeyToken=b77a5c561934e089">
<parameters>
<parameter value="_11963331.Models.ToDoDb_DatabasePublish" />
</parameters>
</databaseInitializer>
</context>
</contexts>
</entityFramework>
I guess that explains why they took a picture of the web.config file changes instead of actually providing the code to type in :-)

See this question. If you leave the deployment connection string as "Remote connection string", and check the "Execute Code First Migrations" box, you will get this exception as the migration connection string, DownloadThisDb_DatabasePublish will not be defined properly. Either specify a real connection string instead of leaving the connection string box blank in the deployment wizard, or define a connection string named DownloadThisDb_DatabasePublish in your Azure site configuration.

Related

EntityFramework DatabaseLogger Interceptor cannot be loaded on server

Adding DatabaseLogger Interceptor as per https://blog.oneunicorn.com/2014/02/09/ef-6-1-turning-on-logging-without-recompiling/
<interceptors>
<interceptor type="System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework">
<parameters>
<parameter value="D:\TempLogging\LogOutput.txt"/>
<parameter value="true" type="System.Boolean"/>
</parameters>
</interceptor>
</interceptors>
Works fine on local, dev and QA boxes but on customer server adding this config throws error
The type 'System.Data.Entity.Infrastructure.Interception.DatabaseLogger, EntityFramework' registered in the application config file as an IDbInterceptor could not be loaded
The EntityFramework.dll is in the server's bin directory.
Any ideas what could be causing the problem on this server? Any other things to check?
This can happen if the drive or path to the file is invalid (or not accessible).
<parameter value="D:\TempLogging\LogOutput.txt"/>
In your case, make sure drive D: and TempLogging folder exist and writable.
In my case this happens under IIS APP when multiple threads are trying to access DB. I could not found simple solution, only turning this DBInterceptor-feature off.

connectionString defaulting to production database.. Entity Framework

I am learning asp.net mvc 4 on top of entity framework. There is a project at work I took over and I am trying to centralize the connection credentials depending on the environment (dev, test, prod) the application is in.
Currently I have the connectionstring dynamic, but for some reason entity framework ignores the connection string initial Catalog setting.
<connectionStrings>
<add name="name1" connectionString="metadata=res://*/Model.csdl|res: //*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="Data Source=001\;Initial Catalog=**;Integrated Security=False;User ID=**;Password=**;MultipleActiveResultSets=True;Application Name=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="name2" connectionString="metadata=res://*/Entites.csdl|res://*/Entites.ssdl|res://*/Entites.msl;provider=System.Data.SqlClient;provider connection string="data source=001\;Persist Security Info=True;User ID=**;password=**;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I have no idea what half of the stuff in the connectionString means, but it is the second connection string giving me troubles, "name2"
Running the debugger shows the base class that extends the ObjectContext called like so,
: base("name=name2", "name2")
I figured Initial Catalog was already set in the connectionstring, "name1" and that would transfer to the name2.. but for the heck of it I added the Initial Catalog to the second connection string and it still defaults to the wrong catalog. I am connecting to the same database server but we have a test and a production database..
What could be overriding this catalog setting and redirecting to the wrong database? When I run my code, I get an innerexception telling me the username (the test database username) doesn't have access to the production database, but I am not sure why the production database is being passed in.
Here is the exception:
The server principal "testuser" is not able to access the database "ProductionName" under the current security context.]
initializing ObjectContext
public Entities() : base("name=name2", "name2")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
This is also in the web.config files:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
Something else interesting I noticed. When I leave the Initial Catalog setting in on the "name2" connectionstring, and set to the test database, and all the credentials are correct, I get the original error as I posted. If I change the initial Catalog to the production name and leave the wrong credentials to log in, I get a log in failed error. Same if I change the credentials around and leave the test database in for the initial catalog. So it seems it's authenticating properly, but something else is a factor once the connection goes through?
For anyone else who stumbles across this problem. I finally figured it out. The other developer was referring to the production database explicitly in all of the stored procedures. I took out all the references and left the implicit call using the "use" statement that was injected implicitly during the export/import process..
Example:
USE [TestDatabase] <---- this goes at top of procedure
Here was an explicit call to the production database:
FROM [productionDB].[dbo].[Table] table
just make it an implicit call like so:
FROM [dbo].[Table] table
If my solution is not the answer for you, I also stumbled across this bug in sql server 2008:
https://connect.microsoft.com/SQLServer/feedback/details/354291/the-server-principal-is-not-able-to-access-the-database-under-the-current-security-context-microsoft-sql-server-error-916

Function imports for entity framework with odp.net managed driver

I recently switched from ODP Unmanaged to ODP Managed (in conjunction with Entity Framework).
The Unmanaged drivers were working fine after adding the necessary information in the web.config section. I could add the stored procedures and generate the complex types using the Function Import - Get Column information (I'm trying to import a stored procedure with an OUT refcursor parameter).
After the switch the config section was updated to reflect the new format and everything works at runtime (so the format is correct).
However when I try to generate the complex types again (or add a new Function Import) I just get a System.notSupportedException Message: The specified type is not supported by this selector) Without any indication which type/selector it is (obviously)...
Google has turned up nothing and the thread on the Oracle Forums has gathered no response as well.
Versions:
ODP.Net (ODAC) : v12.1 (Production release; DLL v4.121.1.0)
EF v5
.NET v4.5
Config file (trimmed a bit):
<configSections>
<section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess"/>
</configSections>
<oracle.manageddataaccess.client>
<version number="*">
<edmMappings>
<edmMapping dataType="number">
<add name="bool" precision="1"/>
<add name="byte" precision="2" />
<add name="int16" precision="5" />
<add name="int32" precision="10" />
<add name="int64" precision="38" />
</edmMapping>
</edmMappings>
<implicitRefCursor>
<storedProcedure schema="ECOM" name="SHP_API_ORDERS.CREATE_ORDER">
<refCursor name="O_RS">
<bindInfo mode="Output"/>
<metadata columnOrdinal="0" columnName="COL1" nativeDataType="Number" providerType="Decimal" allowDBNull="false" numericPrecision="10" numericScale="0" />
<metadata columnOrdinal="1" columnName="COL2" nativeDataType="Date" providerType="Date" allowDBNull="true" />
<metadata columnOrdinal="2" columnName="COL3" nativeDataType="Varchar2" providerType="Varchar2" allowDBNull="false" columnSize="10" />
</refCursor>
</storedProcedure>
</implicitRefCursor>
</version>
</oracle.manageddataaccess.client>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="Oracle.ManagedDataAccess.Client" />
<add name="ODP.NET, Managed Driver"
invariant="Oracle.ManagedDataAccess.Client"
description="Oracle Data Provider for .NET, Managed Driver"
type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.121.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</DbProviderFactories>
</system.data>
The implicit ref cursor config file format is different between Unmanaged ODP.NET and Managed ODP.NET. That might be part of your problem.
To save yourself from pulling your hair out, install the latest Oracle Developer Tools for Visual Studio (ODT) and use the new feature that automatically generates this config:
1) Install ODT 12.1 if you haven't already
2) Find the stored procedure in server explorer, right click it and run it, and enter input parameters.
3) For the output ref cursor that represents the return value for your Entity Function, choose "Add to Config" checkbox.
4) Then select either "Show Config" (and then cut and paste) or "Add to Config".
Here is a screenshot of what I am talking about:
http://i.imgur.com/t1BfmUP.gif
If this doesn't fix the problem, play around with that boolean mapping. I am not 100% sure of this as of this writing, but I remember hearing that support for booleans is another difference between managed and unmanaged ODP.NET. I'm sure it's buried in the release notes or doc somewhere.
Christian Shay
Oracle
Two things you would want to try which might potentially solve the issue:
Ensure the case of the schema name, stored procedure name and the
column names in the config are the same as that in the Oracle.
Try mapping the native type to a more conformant provider type, like
the first column COL1 - map an int32 providerType to the
number(10,0) nativeDataType as enforced by your edmmapping, instead of
the Decimal that you currently have. And so forth for the other
columns (like remove the column lengths) until you do not see the error or get a different one.
I've got the same error and I think my problem is a providerType of DOUBLE or DECIMAL. But, I got one to work that has your 3 column types. Your problem is that a number(10,0) should be a providerType of "Int64".
Stored Procedure:
create or replace PROCEDURE "PROC_ESCC_FIELDS" (p_recordset OUT SYS_REFCURSOR)
AS
BEGIN
OPEN p_recordset FOR
SELECT COL1, COL2, COL3
FROM MyTable;
END PROC_ESCC_FIELDS;
This works and returns the cursor:
<oracle.manageddataaccess.client>
<version number="*">
<implicitRefCursor>
<storedProcedure schema="SERFIS" name="PROC_V_SERFIS_ESCC_FIELDS">
<refCursor name="P_RECORDSET">
<bindInfo mode="Output" />
<metadata columnOrdinal="0" columnName="COL1" providerType="Int64" allowDBNull="false" nativeDataType="Number" />
<metadata columnOrdinal="1" columnName="COL2" providerType="Date" allowDBNull="true" nativeDataType="Date" />
<metadata columnOrdinal="2" columnName="COL3" providerType="Varchar2" allowDBNull="false" nativeDataType="Varchar2" />
</refCursor>
</storedProcedure>
</implicitRefCursor>
</version>
</oracle.manageddataaccess.client>
Click here for a list of the providerType and nativeDataType, etc. ENUMS:

EF5 Code First Migration problems publishing to IIS

I've created a MVC 4 project which uses EF5 Code First with migrations.
Because I was new to this topic I used the following article.
Now that the development is finished I want to publish to IIS (I use FTP or Web deployment package). So before publishing I changed the connectionstring to the right db server.
But after publishing the site I get an exception when accessing pages which make use of the DB. The exceptions refers to the fact that he can't connect to the database.
Because of these problems I decided to try it out locally on another DB server than the default one "(LocalDB)\v11.0". BTW: "(LocalDB)\v11.0" works like a charm...
While debugging I got a better look at the error.
Here is an image of the error:
What I've already tried:
Generate a sql script by executing "Update-Database -Script
-SourceMigration:$InitialDatabase" in the Package manager console. After I ran this script on the dbserver to create the db. Tables were
created but the error was still there.
I changed my connectionstring to all kinds of combination with no
results
I already used a custom user for the app pool in ISS and gave this user full rights to the DB server and the db.
Here is the most important part of my web.config:
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=LOCALHOST\MSSQLSERVER;Initial Catalog=ProjectX;Integrated Security=TRUE;MultipleActiveResultSets=True" />
</connectionStrings>
And
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=LOCALHOST\MSSQLSERVER; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
My DBCcontext class constructor looks like
public DBContext(): base("DefaultConnection")
{
}
I guess I am missing something, this is the first time I use EF Code First with migrations.
This problem is really driving me crazy. I am out of ideas.
Just found out that the problem was caused by the connectionstring.
The string was incorrect, seems like you if you have a default SQL Server you just need to use
"Data Source=LOCALHOST".
I guess because of all the problems I had that day with the deployment i overlooked the easy parts. Yust make sure you the following things are true when you have problems like I did:
Your connectionstring has the same name as your DBContext. Another sollution could be to do like i did and add the connectionstring name to the base:
public DBContext(): base("DefaultConnection")
{
}
If you also have the defaultconnectionfactory set. Make sure to also update the Data Source there. This was one of the problems I struggled with. I didn't check the bottom of my web.config ...
If the problem still persists you can use EF profiler to have a look at the connectionstring when your app of site is accessing the DB.

Using a separate file to maintain the connection string for entity framework

I have my connection string currently in my web.config file.
Is it possible to place it in a separate file and point entity framework to it.
I found the answer here Separate ConnectionStrings and mailSettings from web.config? Possible?:
<configuration>
<connectionStrings configSource="connections.config"/>
</configuration>
With file connections.config containing
<connectionStrings>
<add name="name" connectionString="conn_string" providerName="System.Data.SqlClient" />
<add name="name2" connectionString="conn_string2" providerName="System.Data.SqlClient" />
</connectionStrings>
In case anyone stumbles upon this question. You can put the connection strings in a separate config file using configSource but DONT expect the EF designer to work happily with it.
Every time to go to edit the edmx and 'Update from Database' it will ask for a new connection string and then always want to save it back to the web.config. Not ideal and for me not workable. This is the case in EF6 and previous.