WCF Connected to Entity Framework (Cannot Attach) - c#

I'm using Entity Framework with code-first migration, but after adding a new project to my solution for a WCF service, I get the following error when attempting to run update-database:
Cannot attach the file ...App_Data\MyProject.Data.MyDbContext.mdf'
as database 'MyProject.Data.MyDbContext'.
I've following projects:
MyProject.Data
MyProject.WCFService
The currently temporary solution to this problem is to stop and remove the local db. But why do I need to this, what am I missing? It have worked before without this.
Developer Command Prompt for Visual Studio:
sqllocaldb.exe stop v11.0
sqllocaldb.exe delete v11.0
In Visual Studio:
Update-Database

When you run update-database, code first migrations will attempt to use the connection string from your current start-up project configuration file to connect to the database and perform updates. The easiest way to resolve this in your case sounds like it would be to copy the connection string from your MyProject.Data configuration file to your MyProject.WCFService configuration file. You can also try setting MyProject.Data to the start-up project for your solution, or you can override the parameterless constructor from DbContext in your derived DbContext class and specify an explicit location for a connection string (such as the registry).

Related

How does Package Manager Console know which connection string to use?

I have a website application. Depending on the IsDemoSite setting in my appsettings.json file, the application uses one of two different database connection strings. (One for my main site, and another for our demo site.)
I also have a class library that contains all the Entity Framework models and migrations.
In the Package Manager Console, I set the Default project to the class library.
Then, I can run the add-migration and update-database commands on that class library. But here's the kicker: The IsDemoSite setting for my main application determines which database these commands work with.
How on Earth does Package Manager Console know to what connection string is used by my main application based on the current setting? I'm not running the main application. Package Manager Console is not using the main application as the default project. How the heck does it know which connection string to use?
When you run and add-migration or an update-database command, Package Manager Console will look for the Startup project of your solution and use it as "entry point" for these commands.
Probably inside your Startup.cs class you have the database context injected using the connection string that is stored in your appsettings.json.
I believe you have something like that:
string connectionString;
bool isDemoSite = configuration.GetValue<string>("IsDemoSite");
if(isDemoSite)
connectionString = configuration.GetConnectionString("mainSite");
else
connectionString = configuration.GetConnectionString("demoSite");
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));
add-migration and update-database uses this very same code to determinate against which database it will execute, is something like your application is beign executed to allow this commands to run.
That's also the reason you need some EntityFramework packages installed in your startup project.
I was wondering which appsettings.json would the application use if i used Package Manager Console from Visual Studio 2022. I had appsettings.json, appsettings.Development.json and appsettings.Production.json, each with different connection string.
The one used was appsettings.Development.json.

Copying project does not retain Entity Framework connection

I'm moving my project from one machine to another. I simply zipped the project folder and moved it to my new computer. My project is an asp.net mvc application with Entity Framework. I have my connection string in my web.config file. When I run my application on my new machine, it has trouble connecting to the database it seems.
I get this error when trying to create a dbcontext
[SqlException (0x80131904): There is already an object named 'Merchandises' in the database.]
But the odd thing is it runs perfectly fine on my old machine.
I executed add-migration command and it says I'm very behind in migrations but this is not true.
Unable to generate an explicit migration because the following explicit migrations are pending: [201802070210548_Initial_Migration, 201802130149472_Added_TrackForm, 201802181945057_Added_DOB]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
Any assistance for debugging this would be greatly appreciated.
You can remove all migrations and add only one that named Initial_Migration ( add-migration 'Initial_Migration' and update-database).
--- reference from github.

Is code first migration automatically run on the server?

I am very familiar with Entity Framework using Database First approach and how to deploy the solution with it.
Basically, in my solution with database first approach, I have a web client project that consumes data access library project that is coded with database first approach.
So, first, I write some SQL Server scripts to add new tables (or make schema changes).
Next, go to the data access library project, using EF edmx designer to update .net from existing database, compile this data access layer, and the DDL reference is automatically updated in the client web project.
When I deploy the solution to the production server:
First, I need to run the t-SQL scripts on the production SQL server
Next, I deploy the 2 updated DDLs (one for the web and 1 for the data access layer) on the web server.
Now, I have a new application that includes a web project and a data access layer project that uses EF Code First approach.
I am new to EF code first approach. I know any time when I change the database schema, for instance adding a new table, I need to run code first migration in the Package Management Console in Visual Studio to let my back-end database instance change/update.
My question:
When I deploy the application to the production, what are the steps I should follow?
How is the production SQL server updated that is created with EF Code First approach?
Is it a automatic process or I have to run the migration manually like I do inside Visual Studio under the Package Management Console?
Thanks.
If you're using Azure then you can configure it has automatic process as shown below.
Else you have to do it manually like this :
You have to create a db script and after that you can run it on your production db.
PM> Update-Database -Script
You can refer this doc : Getting a SQL Script
Another option where I normaley use :
When I need to run migrations aginst the production db,I change my conn string to reflect production db and after that run :
PM> Update-Database
You have several options with migrations.
You can generate a script using Update-Database -Script (as #Sampath notes)
You can run Update-Database -ConnectionString="YourDbString" and it will do it against the production database for you
You can use a migration initializer and on app startup it will use the applications connection string to run the migration. Do this by putting a line similar to this in your initialization routine:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
Where Context is your DbContext type and Configuration is the configuration class generated when you made the first migration.
See this MSDN article for more information: https://msdn.microsoft.com/en-us/data/jj591621.aspx

Where is the mysterious EntityFramework database?

In my main project, I have configured a connection string to my database like this:
<add name="DefaultStoreConnection" "provider....">
In my infrastructure project, I have a database context with a default constructor that passes the connection name to the base class:
public DatabaseContext() : base("DefaultStoreConnection") {}
As soon as my application starts, EF generates a 'store.sdf' (SQLCe database) in the application output folder (\bin).
Now, I wanted to reset all migrations and start with a plain database. I deleted the 'store.sdf' in the \bin directory, deleted all migration files and then called in the Package Manager Console:
Enable-Migrations -Force -ProjectName "MyInfrastructureProject" -StartUpProjectName "MyMainProject".
This worked fine, a new migrations configuration class was generated. Then I ran:
Add-Migration Initial -ProjectName....
And then the following line appears:
A previous migration called 'Initial' was already applied to the target database
Where? Where does this migration has been applied to? Where can I reset this 'migration'?
It should be in a folder containing all the migrations, but it's possible that it's deleted after it has been applied to database. You can see list of applied migrations in __MigrationHistory table of your target database. If you wish to rescaffold the database, empty the __MigrationHistory table.
I run to the same problem as you. After a day of google search without a single useful help, i figured it out myself that this is Visual Studio bug where your solution have more than one Mvc projects. The add-migration will check on the older Mvc project to create migration file for your current project (that is why i call it BUG).
To avoid this, you should only use one Mvc project per solution.
Have a look at the app_data folder of your project.

How to enable Code First Migrations in ASP MVC app?

I have ASP.NET MVC4 app with Entity Framework Code First approach. I've moved my DbContext inheritor to separate Model project recently (I've copied connection string from web.config to the app.config).
Now when I'm trying to run my app I've got error that my database should be created directly through Code First or Migrations. First way is not suitable for me because I have remote DB server (I've created it through hoster's control panel).
But when I'm trying to enable Migrations I've got error that No context type was found in the assembly 'MyProject'. This is obviously happen because my DbContext inheritor not placed in the start project.
So how can I indicate to look context class in separate project?
By the way, I have DropCreateDatabaseIfModelChanges<> initializer for my DbContext inheritor.
In the Package Manager Console, if you run Get-Help Enable-Migrations, it will show you all of the advanced options. Included in those are:
-ProjectName (the project to run this command against, i.e. to look for the context type)
-StartupProjectName (the project which has the app.config/web.config where the context runs, i.e. where your connection string lives). This one is important unless your Model project has the correct connection string in its own .config file.
-ConnectionString (the connection string to use while scaffolding the migration if you want to override the value)
When you're using Add-Migration it should support the same options.
You can also change the Package Manager Console's Default Project dropdown to run against your model project by default.
If you are using Package Manager Console you can choose a default project where entity framework will search your DbContext.

Categories

Resources