mvc publish error with automigrations - c#

I'm having problems publishing my MVC project.
I got the error "The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).", that was solved with the help of automigrations.
I published my project via ftp on the another machine, then added some changes on the model`s structure, run it on my computer, it launced succesfull and published again on the same another machine. When I tryed to run it there, an error occurred - "The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269)."
I'm using IIS7 on Windows 7.

To update database on another Db server you could make this way:
Configure connection string to use new server
Run Update-database command from package manager console, in some cases you will need to use -force flag. But be careful this could delete some your data. Also this command has - ConnectionStringName parameter this could help you to make updates.
This is a very bad approach and I don't recommend update database this way.
I would recommend you set up Initialzier for your context. I usually use MigrateDatabaseToLatestVersion and after changing your model you will need to add new migration, using Add-migration command.
To set up it use this command in application start method:
Database.SetInitializer<ApplicationDbContext>(new MigrateDatabaseToLatestVersion<ApplicationDbContext>());

You must update your database after changing the model. Another machine and your computer use the same database? If not you must update this database.

Related

C# Entity Framework error when MSSQL server has View any database = denied

We use MSSQL for our C# .NET Framework 4.8 Application using Entity Framework for database related activities.
But on our production environment the SQL server has the Securable: View any database on Deny.
The database for the application exists but Entity Framework cannot see the database and tries to create it, this results in the CREATE DATABASE permission denied in database 'master' error.
I am using CreateDatabaseIfNotExists and MigrateDatabaseToLatestVersion in my Application_Start().
Now the issue (I think) lies with CreateDatabaseIfNotExists.
For the first run we give the db user enough rights to create and fill the database, it does this without problem.
But after the initial setup we remove those rights and the issue starts.
It tries to create the database, But it already exists.
And I am hoping there is a way to have both Automatic database creation/migration, and the View any database on deny securable.
Does anyone have a idea on how to solve this issue?
Is there some sort of option I could enable to stop this behaviour?
You should "wire in" IHostingEnvironment and make sure you run
CreateDatabaseIfNotExists and MigrateDatabaseToLatestVersion
only in certain environments.
===========
For DotNet-Core (NON asp.net-core) apps.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.hosting.internal.hostingenvironment?view=dotnet-plat-ext-7.0
for asp.net-core.
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.iwebhostenvironment?view=aspnetcore-6.0
....
Then you will use (probably an existing)
"Is" method:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.hosting.hostingenvironmentextensions.isdevelopment?view=aspnetcore-7.0
IsDevelopment
IsProduction
IsStaging
or you have the ability to "add your own environment".. with
IsEnvironment(string)
I would NEVER leave to "auto-voodoo" what might happen to the production database.
You can see this approach:
https://stackoverflow.com/a/60399887/214977

How can I specify a location to create database files for an Entity Framework Core application?

I have an application using Entity Framework Core to create an SQL Server database and its tables by applying migrations. I need to be able to specify the directory location where the database files will be created.
What I want to be able to do is either:
Have my application create the database with its files in the specified location before applying migrations
Have my application tell SQL Server where to create the database files, before applying migrations
I'm creating my DbContext using the connection string:
Data Source=ServerName;AttachDbFilename=specifiedPath\databasename.mdf;Initial Catalog=databasename;Integrated Security=True
I've tried having the application create the database using a standard SQL Create query before applying migrations. This causes the migrations to fail with the following exception:
Microsoft.Data.SqlClient.SqlException (0x80131904): Database 'databasename' already exists. Choose a different database name.
I assume this is because the DbContext or migrations are trying to create the database specified in the connection string.
Could I somehow edit the migration to remove the step where it creates the database? Or the DbContext?
Just in case anybody is looking to solve a similar problem:
I solved this by simply removing my code that checked if the database already existed. There's actually no need to manually create the file at all.
By specifying the file name in the connection string, using the
AttachDbFilename=specifiedPath\databasename.mdf
parameter, SQL server just created the file in that location.

Scaffold (reverse engineering) existing database return empty sets

I followed the instruction from Microsoft to scaffold an existing AzureSQL database and WAS SUCCESSFULLY access to data before. Here was the command I used
"PM> Scaffold-DbContext "Server=tcp:******.database.windows.net,1433;Initial Catalog=******;Persist Security Info=False;User ID=******;Password=******;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models>
However last week my company change the password of the database and all of sudden the Db Context model stop working. I have updated the connection string correctly and even re-scaffold the models however it still not working. Note that I tried to connect through SqlConnection with that connection string or login into SQL Sever Explorer and they are still all successful. The data team said they only changed the password and nothing more. However, only with EF core no longer work. There is no message error but if I create an object DbContext and see that 99% of the dbsets are empty. Below is my debug photo.
Has anyone face the problem before and can help me with that. Thanks in advance. I am new.
Congratulations you error is solved by yourself:
The problem come from csproj file I set enable. If I remove it then everything work fine again.
I help you post it as answer and this can be beneficial to other community members.

SQL Server LocalDB: after detach and re-attach database to same computer(machine, same path), cannot backup database

My development environment is C#, SQL Server 2014 LocalDB, SQL Server 2012 Express, Windows 10, Visual Studio 2015.
When users of my application need to move their localDB (.mdf) file to another place, another computer (LocalDB server), detaching from computer A and attaching to computer B and then, we can run BACKUP database command successfully.
However, in case users mistakenly detached or users changed their mind to use continuously in computer A, my application has to be able to re-attach the detached LocalDB database file (.mdf) to the same computer (same LocalDB server).
When I run BACKUP DATABASE command after my application re-attached the database file to same computer successfully, error message shows as,
Unable to open physical file, The process cannot access the dbfile because the dbfile is in use by another process
BACKUP DATABASE terminated abnormally
So, I entered Microsoft Server Management Studio and can see 2 dbfile with specific name as first is greendb.mdf (only name), second is c:\users\kay\appdata\greendb.mdf (with full path).
I think the c:\users\kay\appdata\greendb.mdf (with full path) is created when the database is detached. And when I click it through security-login-kay-user mapping, unlike other databases show their permissions inside, the detached database with full path doesn't show their permissions and show error message like,
Unable to cast 'System.DBNull' object to 'System.String' (Microsoft.SqlServer.Smo)
It seems Microsoft LocalDB Server still recognizes the detached database with full path and is confused with newly attached database (only name without full path).
Any excellent ideas will be highly appreciated !
Thank you so much !
In detaching localDB,
we have to run ALTER DATABASE ROLLBACK IMMEDIATE command first to terminate all the incomplete transactions.
Just to explain easily, Before we close a Restaurant, we have to announce to the customers in the Restaurant, 'This Restaurant will be closed very soon, please complete your eating and get outside before closing of Restaurant'
If you're needed to re-attach the localDB to same computer(same localDB Server),
Some activities like these have to be avoided to prevent the ghost(bug?).
1) Trial to open the localDB in code programmatically
2) It seems counting with the name of detached localDB also reminds the existence of localDB to the localDB Server.(SELECT COUNT dbname command in master database)
Strange thing which has to be fixed as a bug is,
if we detach a localDB from master DB, I think it has to be not able to open the detached localDB in code programmatically. However, code like SqlConnection.Open(); runs and pass by without any exception(error) and immediately the fullpath ghost is created.
It seems the name of detached localDB is deleted on master DB but the Server connects the detached localDB through the physical path in the provided connectionstring.
And to decide some localDB is needed to attached or to check it's detached or not, I've developed my own solution(simple code) to do this.
Hope my experience helps someone else.
Well, I worked a lot using attach and detach operation and finally I figured out that the best practice for us as a developers is working with scripts.
So, if you want to (detach) your db to re (attach) again either with a new name or the same name. I suggest you to generate scripts for your database and script it again.
if you run the script directly you will get an error because you have to delete the old data (the old / new have the same name) and script by default is using the db name which is written in the first line, sure you can remove this line and use the new database you want to use.
for scripting database including data, make sure to set preference from the wizard (Advanced settings => schema only / data only / schema and data.) choose schema and data
By default the choice is schema only.
choose a destination for your sql file, after running the script and deleting the old data. your backing up process should go with no problems.

Entity Framework 5 : changing the database connection

I have a made an EntityFramework model based on my Demo Database.
I want to include connection strings for Staging and production and then in my Console App prompt the user to see which database they want to perform the operation on.
When I was prompted to setup the EF.edmx file I just chose to store the connection string in the app.config file. I have seen a link to change the Connection string of EntityFramework Context when initializing it here
However when I store another connection to my Staging Database, I get an error "Keyword not supported: 'metadata'"
So I stripped down the connection string not to include the EntityFramework type of parameters such as metadata=res://*/MyDBItems.csdl|res://*/MyDBItems.ssdl blah blah
and used a very simple database connection string
data source=myDB;initial catalog=myDB;user id=myUser;password=myPass;MultipleActiveResultSets=True;
now my Context does instanciate but when I get to a query I get another error about:
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.
How can I switch between different databases with Entity Framework 5, thanks!
forget it I got it....what I did...I made a 2nd constructor in the Context.cs file
public MyContext(string dbModel) : base("name="+dbModel) {
}
then in my app.config I have the various settings for the Demo,Staging & Production database connections....this took the full entityframework connection string. I think the link I provided was for Code-First but I am using Database First.

Categories