Changing connection string after moving database to App_Data folder? - c#

I am trying to learn mvc.net. I created a small project in which I used Model first approach. The problem is I wanted my database to be shown in App_data folder for that I followed this article:
http://www.dotnetfunda.com/articles/show/2182/how-to-embed-sql-database-in-appdata-folder
In short I detached the database and then I include the database in app_data folder. Now I am facing problem in changing the connection string, Previously I generated connection string automatically using entity framework, It was like:
<add name="KeepitrememberEntities"
connectionString="metadata=res://*/EDM.csdl|res://*/EDM.ssdl|res://*/EDM.msl;
provider=System.Data.SqlClient;provider connection string="
data source=mypcname\SQLEXPRESS;initial catalog=Keepitremember;
integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
and now I changed it to:
<add name="KeepitrememberEntities"
connectionString="Data Source=mypcname\SQLEXPRESS;
AttachDbFilename=|DataDirectory|Keepitremember.mdf;Integrated Security=True;
User Instance=True"
providerName="System.Data.SqlClient" />
When I am executing the code and trying to save the value using a form, it's showing me the error in EDM.Context.cs and error is:
An exception of type
'System.Data.Entity.Infrastructure.UnintentionalCodeFirstException'
occurred in Emptymvc.dll but was not handled in user code
Additional information: 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.
What I need to do now, any solution!!
Thanks for your time.

As far as I see, the first connection string is Entity Framework connection string, and the second one is SQL Express connection string. In an EF project, both of them should be exist in web.config file for DbContext and code generation template usage - hence they're not interchangeable (i.e. you should not change EF connection string into SQL Express one and vice versa).
Since you have changed EF connection string contained CSDL, SSDL & MSL information required by EF into SQL Express one, EF assumes the existing database metadata isn't exist anymore and trying to create a new database like Code First has, hence it triggers UnintentionalCodeFirstException after executing OnModelCreating method.
Instead of changing EF connection string in web.config, just add SQL Express connection string on the same connectionStrings element as this (you may need to define initial catalog name when required):
<connectionStrings>
<!-- SQL Express connection string -->
<add name="KeepitrememberConnection"
connectionString="Data Source=mypcname\SQLEXPRESS;Initial Catalog=Keepitremember;
AttachDbFilename=|DataDirectory|Keepitremember.mdf;Integrated Security=True;
User Instance=True"
providerName="System.Data.SqlClient" />
<!-- EF connection string -->
<add name="KeepitrememberEntities"
connectionString="metadata=res://*/EDM.csdl|res://*/EDM.ssdl|res://*/EDM.msl;
provider=System.Data.SqlClient;provider connection string="
data source=mypcname\SQLEXPRESS;initial catalog=Keepitremember;
integrated security=True;MultipleActiveResultSets=True App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
NB: The connection string names should be same with predefined names in EF model generation schema.
Related issues:
Model First with DbContext, Fails to initialize new DataBase
Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode
Entity Framework cant use the DbContext, model being created

Related

Support multiple database using Entity Framework 6.0 with connection string transforms

I've a Web API project which uses EF 6.0 for database operations. I have 3 different Azure SQL databases (Dev, Test, Prod).
I have been able to create an Entity Data Model with data first approach.
I've used configuration manager of VS2017 to create a web.test config file, but transformation of connection strings isn't working.
Currently my web.config file has the connection string that points to Dev environment as follows:
<connectionStrings>
<add name="ProjectDbEntity"
connectionString="metadata=res://*/Data.ProjectEntityModel.csdl|res://*/Data.ProjectEntityModel.ssdl|res://*/Data.ProjectEntityModel.msl;provider=System.Data.SqlClient;provider connection string="data source=company-ai-Projectserver.database.windows.net;initial catalog=company.DB_Dev;persist security info=True;user id=Project;password=Password1234$$;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
And, web.test.config is as follows:
<connectionStrings>
<add name="ProjectDbEntity"
connectionString="metadata=res://*/Data.ProjectEntityModel.csdl|res://*/Data.ProjectEntityModel.ssdl|res://*/Data.ProjectEntityModel.msl;provider=System.Data.SqlClient;provider connection string="data source=company-ai-Projectserver.database.windows.net;initial catalog=company.DB_Test;persist security info=True;user id=Project;password=Project1234$$;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient"
xdt:Transform="SetAttributes"
xdt:Locator="Match(name)"/>
</connectionStrings>
I'm not able to figure out how do I make EF change connection string, when I'm using it to build a EF model using one instance of database, but during deployment I want to use other database instances with the same schema.
I've been reading up on the following post, but somehow not able to make it work.
EDIT: I found the solution. All I had to do is select Publish option, then Settings and again select Settings on the popup, and finally select the configuration from the drop down option to the desired configuration. It seems selecting the configuration on the main menu does not publishes the same environment unless explicitly selected.
I found the solution. All I had to do is select Publish option, then Settings and again select Settings on the popup, and finally select the configuration from the drop down option to the desired configuration. It seems selecting the configuration on the main menu does not publishes the same environment unless explicitly selected

EF 6 OnModelCreating is called when I open MainWindow.xaml

I have an Entity Framework 6.1.3 application that uses Database First.
The application works and I get the data I want from the database.
The problem is that when I open (double click) MainWindow.xaml I get this error:
UnintentionalCodeFirstException: The context is being used in Code First
mode with code that was generated from an EDMX file for either Database
First or Model First development. This will not work correctly. To fix
this problem do not remove the line of code that throws this exception.
If you wish to use Database First or Model First, then make sure that
the Entity Framework connection string is included in the app.config or
web.config of the start-up project. If you are creating your own
DbConnection, then make sure that it is an EntityConnection and not some
other type of DbConnection, and that you pass it to one of the base
DbContext constructors that take a DbConnection. To learn more about
Code First, Database First, and Model First see the Entity Framework
documentation here: http://go.microsoft.com/fwlink/?LinkId=394715
So EF is calling OnModelCreating(..)
Which it shouldn't!
The connection string from app.config:
<connectionStrings>
<add name="AuthorBookEntities" connectionString="metadata=res://*/AuthorBook.csdl|res://*/AuthorBook.ssdl|res://*/AuthorBook.msl;provider=System.Data.SqlClient;provider connection string="data source=LENOVO-PC;initial catalog=BOOKS;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
All the EF code is as created by the T4 scripts.
The application is one WPF program, no dlls or anything...
What could be wrong?

Server Explorer shows both dbContext and database.mdf active

I may have just confused the implementation of the database to my ASP.NET MVC project, but I have a separate data layer with a connection string pointed to a .mdf file.
I then imported the data models through the ADO.NET Entity Data Model code-first to existing database.
When I go to enable migrations, no problem.
However, now I'm trying to Add-migration, and I get:
Unable to generate an explicit migration because the following
explicit migrations are pending: [201504081848445_InitialCreate].
I checked my server Explorer, and noticed that I have both "DatabaseContext" and a Database.mdf showing up. Sorry if this is a completely elementary question, but my suspicion is that it has something to do with my connection string? I saw that when I first enable and initially create migrations, it does show up in my DatabaseContext. But the next day, I see "databaseContext" missing the _migrationHistory, and I see the error message that the explicit migrations are pending.
My connection string:
<connectionStrings>
<add name="DatabaseContext"
connectionString="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"
providerName="System.Data.SqlClient" />
</connectionStrings>
EDIT 1
Now i'm having trouble enabling and updating the database migrations. I've re-imported the data model code-first, and re-enabled migrations.
I see that now DatabaseContext contains only the table _MigrationHistory, and nothing else. My .mdf has all the tables except for _migrationHistory.

Code-First Migrations for multiple databases?

I have the following connection string:
<?xml version="1.0" encoding="utf-8"?>
<connectionStrings>
<add name="MyContext" connectionString="metadata=res://*;provider=System.Data.SqlClient;provider connection string='data source=SQLSERVERDB;initial catalog=TestDB_CodeFirst;user id=***;password=***;MultipleActiveResultSets=True;App=EntityFramework'" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
When I try to enable migrations I first get a warning:
Cannot determine a valid start-up project. Using project 'MyApp.Model' instead.
Your configuration file and working directory may not be set as expected.
Use the -StartUpProjectName parameter to set one explicitly.
Then I get this exception:
Argument 'xmlReader' is not valid. A minimum of one .ssdl artifact must be supplied.
Is the connection string wrong and why should I need ssdl if I'm using Code First?
NOTE
My context is in MyApp.Model project where my Migrations folder should be located.
I don't have connection strings in my main startup project because connection strings are retrieved from a second database and the user can select one of them when logging in to the application.
I have just one connection string shown above in my MyApp.Model project which points to my development database.
Also, my second question is:
If I use CF migrations, will all databases be migrated each time a user selects a different database for the first time?
EDIT
I changed the connection as mentioned below, and I get the following exception:
The item with identity 'table1' already exists in the metadata collection.
Parameter name: item
It must be noted that I reverse-engineered an existing database. So I don't know what possibly went wrong!
I've also deleted the Migrations folder and checked the database but there is no migration_history table created.
You are trying to use a connectionString designed to work with Database First / Model First. You can tell because your providerName is System.Data.EntityClient instead of System.Data.SqlClient.
Your connection string should look like this:
<connectionStrings>
<add name="MyContext"
connectionString="Data Source=SQLSERVERDB; Initial Catalog=TestDB_CodeFirst;user id=***;password=***;"
providerName="System.Data.SqlClient" />
</connectionStrings
Although I would suggest using Integrated Security instead of a user/password. Just personal preference, though.

Entity Framework 6 Error Unable to load the specified metadata resource

I'm using Entity Framework 6 and "model first" in my solution, I separated my "Data Model" classes into another project, so that I can add reference to the "Data Model" classes without exposing my "Data Model Contexts" and connections.
I don't want to expose my Entity Data Model project (especially the DB Context etc) to my UI Layer. I have this:
I have now successfully separated my auto generated entity classes from my data model, I tried it this works by adding an entity or a property to an entity is updated in the project Mapeo.BusinessEntity.
This is my connection string from DatabaseLayer (Mapeo.DatabaseModel)
<connectionStrings>
<add name="MapeoModelContainer" connectionString="metadata=res://*/MapeoModel.csdl|res://*/MapeoModel.ssdl|res://*/MapeoModel.msl;provider=System.Data.SqlClient;provider connection string="data source=raranibar\ral;initial catalog=Mapeo;user id=sa;password=*****;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
In my service layer I it copied this connection string to the App.config, my problem is this when I want to add a data I have this message: Unable to load the specified metadata resource How I can resolve this problem?
Updated
I found the solution, I changed the connectionstring in App.Config the pretentation layer I replaced in the connection strign "*" for the directory of DataModel in my case (Mapeo.DatabaseModel) this is now my connection string in layer presentation:
<connectionStrings>
<add name="MapeoModelContainer" connectionString="metadata=res://Mapeo.DatabaseModel/MapeoModel.csdl|res://Mapeo.DatabaseModel/MapeoModel.ssdl|res://Mapeo.DatabaseModel/MapeoModel.msl;provider=System.Data.SqlClient;provider connection string="data source=raranibar\ral;initial catalog=Mapeo;user id=sa;password=scugua;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
Update your connectionString with correct path if you've such like issue to load metadata files. May it help someone else...
connectionString="metadata=res://DatabaseModel/MyModel...
When you copy an EDMX from one project to another, you must be careful with the name of the folder where you originally created the EDMX, because it's reflected in the app.config (or web.config), in the connection string related to the metadata resource. Like this:
//Initial model created in Folder1 in the original project
<add name="DataModelContainer" connectionString="metadata=res://*/Folder1.ServerModel.csdl|res://*/Folder1.ServerModel.ssdl|res://*/Folder1.ServerModel.msl;provider=System.Data.SqlClient;provider connection string= .../>
//Then manually copied to Folder2 in other project
<add name="DataModelContainer" connectionString="metadata=res://*/Folder2.ServerModel.csdl|res://*/Folder2.ServerModel.ssdl|res://*/Folder2.ServerModel.msl;provider=System.Data.SqlClient;provider connection string= .../>
After creating the entity if the database edit, entity does not work
As long as the entity update
In this way:
If this method did not work
It is better to do:
Remove this tag: <add name="MapeoModelContainer" ...
Remove MapeoModel.edmx
Add ADO.NET Entity Data Model
Then use the wizard to create a connection and entity
If this method did not work either send Inner exception

Categories

Resources