Update-Database Always updating in .\SQLEXPRESS, in Entity Framework - c#

I have a solution project in in which I have implemented Entity framework in a class library Project.
I have a App.config file in the same class library in which I am giving my connection string as
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=DDC5-D-4R03T72;Initial Catalog=ServiceAdaptor;User ID=sa;Password=pwd;MultipleActiveResultSets=True;Integrated Security=False"
providerName="System.Data.SqlClient"/>
</connectionStrings>
(I am using Visual Studio 2010, and I am using Code-First Approach EF)
Now the problem is when I run command "Update-Database -Verbose",
It is not creating tables in above DB , rather it creates in .\SQLExpress which I didn't mentioned in anywhere in my soln)
when I gave command like
Update-Database -Verbose -ConnectionStringName "DefaultConnection"
it gave me message
"No connection string named 'DefaultConnection' could be found in the
application config file."
What I conclude is my Update-Database command is not able to get the connection string from config file.
Not able to figure out,What is wrong.

Finally I found the solution, There Problem was here that somehow Update-database command was searching Connection string in Web.Config file not in App.Config file as in my Case I have Class library project which has App.config file.
Since It did't get the Connection string By default EF framework in VS 10 will assume .\SQLEXPRESS as default db and create the tables there.
So the solution I found is:
1) Add reference System.Configuration in the project
2) Insteed of using base("DefaultConnection") in dbContext use as below
base(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)

Related

Migrating multiple DbContexts in two different projects in the same solution

I have two seperate projects in the same solution. One is a windows sevice and the other is a ASP.Net application. The solution doesn't have a seperate data layer. The projects communicate to its own separate database. In the second project which is the web application when i try to do a Enable migration with the following command in the "Package Manager Console", I get an error.
The command:
enable-migrations -ContextTypeName ServicesMock.Data.MockContext -
MigrationsDirectory:MockMigrations
The error refers to the first project and says that the context type "ServicesMock.Data.MockContext" was not found in the assembly "Assembly of the first project in my solution"
How can i sought this out so that the migration command can be pointed to the relevant project ?
I was referring to this link to create the commands.
I tried changing the startup project as well.
Updated (added this section)
Corrected the issue of not selecting the proper Default Project in the package manager console.
In the first Project (Windows service) the Application.config file contains the dbcontext for that project
<connectionStrings>
<add name="ApplicationDbContextConnection" connectionString="data source=abc;initial catalog=serviceDB;user id=;password=;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient"/>
</connectionStrings>
The purpose of the second project (Web Application) is to mock some External API references used in the first project. It doesn't have a application.config, instead a web.config.
It has its own DbContext. I have added the connection string in the web.config which is
<connectionStrings>
<add name="MockContext" connectionString="Data Source=abc;Initial Catalog=mockDB;Persist Security Info=True;User ID=;Password=" providerName="System.Data.SqlClient" />
</connectionStrings>
But now when I try to EF migrate the 2nd project(Web Application) , I get an error "No connection string named 'MockContext' could be found in the application config file." But the web application does not use a app.config file. Is it referring to the 1st project ?

EntityFramework through Class Library

I have a class library called DataManip, a webform project and a winform project.
DataManip is a class that will contain all the necessary methods to manipulate the database, including handling migrations and database updates.
The .mdf database is also inside the DataManip project.
The problem that I am having right now, is that when I setup a connection string in the App.config file of DataManip, it doesn't recognize the |DataDirectory| substitution string.
Connection string :
<add name="Context" connectionString="Data Source=(LocalDB\v11.0;AttachDbFilename=|DataDirectory|DB\mydatabase.mdf;Integrated Security=True providerName="System.Data.SqlClient" />
Harcoding the path in AttachDbFilename will successfully generate the database, but working with team members make this approach not possible.
The error message that I get when I try to run update-database in DataManip is :
A file activation error occured. The physical file name '\DB\mydatabase.mdf' may be incorrect...
How can I get the DataDirectory substitution string to work in a class library?

No connection string named could be found in the application config file

I'm using EF and generated .EDMX from it but then I only wanted it to be used for automated generation of Class Files.
I then used the Class Files to create a Entity Model and then created a DB Context and then Repository. I'm calling a WebApi (which is in a separate project but same solution) to access the repository to GET data. While I run the WebApi, I'm getting the error,
{"No connection string named 'DBEntities' could be found in the application config file."}
But within my DAL, I have a webConfig and that has the following entry so I'm not quite sure what has gone wrong,
add name="DBEntities" connectionString="metadata=res://*/Models.DBModel.csdl|res://*/Models.DBModel.ssdl|res://*/Models.DBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MY-PC;initial catalog=DB;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient"
In the DBContext file, remove
public RaficaDB()
: base("name=DefaultConnection"){}
to
public RaficaDB()
: base("DefaultConnection"){}
EF 4.3, EF 5 and EF 6 do not like the connection string being called name=xxxxx
Answer found here -> No connection string named 'MyApplicationEntities' could be found in the application config file
You say "within my DAL, I have a webConfig". I guess the connection string is in the configuration file of a referenced class library, but not in the main configuration file you have in your entry project (a web api project, I guess looking at the tags).
If so, just copy the connection string in the entry project configuration file.
Insert following section in the configuration section of the .config file of the same project where your .edmx file is under.
You may also create different connection string for different environment in the .config file of the main project and pass any of the connection string as parameter of the constructor of the DBContext.
<connectionStrings>
<add name="DBEntities" connectionString="metadata=res://*/Models.DBModel.csdl|res://*/Models.DBModel.ssdl|res://*/Models.DBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MY-PC;initial catalog=DB;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
Setting the project as Startup project worked for me
I found that this worked:
1) Check if you have several "App.config" files.
2) Check if has a wrong name than the connection string it has to use.
3) Save the project and run the program
It should work now.
Copy and paste the connectionstring to your WEBAPI Project web.config file will solve the issue.
It's dumb, but I had this error that was fixed by a Rebuild All !!
Might as well have turned it off and on again....
If none of the above fixes the issue, then probably you are doing the mistake I did, here was my case:
I have multiple projects in my solution and the Startup project was different than the one having the entity framework, switching project from the package manager console seems like a buggy thing especially in entity framework commands, so here what I did:
Set your webapi(Or the project has the entity framework) as a startup project.
Rebuild the solution and try again.
Run the entity framework command again.
If the above doesn't work then try to close the solution and try from Step 2, this should fix it.
The easiest solution:
Remove current edmx file and related connection string in app.config
and add Edmx item with same name as previous again.
this worked for me.

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.

Not using database connection string

I have google'd the crap out of this problem, I cannot find a solution.
Using EF code first approach against a domain assembly, being consumed by a .net web application.
in the domain project there is a app.config, in there I have the following connection string for EF
<connectionStrings>
<add name="DefaultConnection" connectionString="Initial Catalog=easyDayTea;Data Source=localhost;user=sa; password=12344321" providerName="System.Data.SqlClient" />
Then in the context class TeaDb.cs I have the following constructor:
public TeaDb()
: base("name=DefaultConnection")
{
}
I have also tried just using "DefaultConnection" by itself in the constructor.
The problem:
Everything was fine until EF decided it wasn't going to take notice of additional classes/tables added to the context, so I removed EF from the project by deleting the migrations folder and empting the database of tables, then re ran enable-migrations and then the web application project to make EF do it's stuff to the database. However it did nothing!
When I run the web application though it works! and there is data (from the seed) in the tables, however not in any database i can see! It must be using a portable sql file, which doesn't make sense as I have it configured for a specific database / server by use of the configuration string.
I have also tried specifically specifying the connection string to use by doing a:
update-database -ConnectionStringName DefaultConnection -f
Still no joy.
If anyone could help me it would be amazing!
Thanks,
Xavier.
You'll find your database at Users\[youruser]\[Name you passed in your context constructor].mdf
app/web.config are only used if they are in the main project, if you have an app.config/web.config outside your main project it will not be used (some templates add them, but they are meant to be used as an example).
Check this answer for a similar problem with EF4
EF doesn't use the connection string from the app.config in the class library. It will use the connection string from the web.config in your web application. If you don't have the connection string defined in your web.config then it might be using conventions to attach the database with LocalDb in your App_Data directory.

Categories

Resources