An attempt to attach an auto-named database for file [...] failed. A database with the same name exists [...] - localdb

Using LocalDB for developing an Entity Framework project yields the following error when ...
using class Initializer : DropCreateDatabaseIfModelChanges<Context> with Entity Framework 6.4
calling Database.EnsureDeleted(); Database.EnsureCreated(); with Entity Framework Core 3.1
The error message
An attempt to attach an auto-named database for file D:\Documents\Visual Studio-Projekte\EF-Test\bin\Debug\netcoreapp3.1\EF-DB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
The Connection
Context db = new Context(#"Server=(LocalDB)\MSSQLLocalDB;Integrated Security=true;AttachDbFileName="
+ Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"EF-DB.mdf"))
What is the cause for this exception to happen?

This happens when you clear your solution.
When you clear your solution, the .mdf/.ldf files get deleted along with the \bin\ directory, yet SQL Server Express LocalDB's master database keeps a reference to the (deleted and now missing) database files.
Apparently, neither database initializers in Entity Framework 6.4 nor the database creator in Entity Framework Core 3.1 handle this situation without throwing above error message.

Related

EF 7 Migration to Existing Database

I am working on a web project using ASP.Net 5 and EF7.
I have imported all the tables from existing database onto my models in my project. However, I am having problems in regards with migrations.
I have created the initial migration, made some changes on particular entity, create another migration following the changes I have made and now want to apply the changes on the database.
After running this command below:
dnx ef database update [Migration]
the dnx is trying to apply the 'initial' migration with all the entities which are already in database and this causes an error as below:
{ There is already an object named ['EntityName'] in the database. }
Can you please advise on how to do the migration on the existing database?
Thanks
Saeed
In EF6 you would run a migration with the -IgnoreChanges flag and it would take a snapshot of the model without any Up() code. This is missing from EF 7(EF Core) as indicated here.
The workaround for now is delete or comment out the code for existing database objects from the Up() code of the migration and then update-database. Subsequent migrations will then include only the changes.
After 2 days I found a way for EFCore that is not in google and internet!
How My steps works?
When you have a database with 10 table and you have data in tabales that you don't want to clear's data.and after this you will create new models in your code first and runnig to existing database and you will get error "Invalid object name 'tableName'." for query to new tables and you want to create migrations and do update it to existing database but first migration will create all queries for old and new tables if you run update-database you will get "There is already an object named ['EntityName'] in the database." for your initial migration.
How fix it?
Delete all migrations and snapshot in you database project
Delete __EFMigrationsHistory table in your existing database (if exist)
Run in Package manager console:
Note before run: This code will create new context and models of your existing database to Data folder so don't forgot to check you have not Data folder in your project.
Scaffold-DbContext "your connection string"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Data
Run in Package manager console:
Note before run: Create first migration for initial database with Data folder context (OldDataBaseContext is inside of your Data folder that created by step 2)
Add-Migration initial -Context OldDataBaseContext
Delete all code in Up method inside of created initial migaration in step 3
Run in Package manager console:
Note before run: Update databse with Data folder context (OldDataBaseContext is inside of your Data folder that created by step 2)
Update-Database -Context OldDataBaseContext
Delete data folder that created in Step 2
Go to snapshot and initial migration classes and change the deleted context from Data folder to main context that is exist in your database project (just fix it for build)
Run:
Note before run: Add migration for main context that have new database changes
Add-Migration newUpdate
Run:
Update-Database
I Hope this help someone.
If you are strongly believe, that new (EF7) database schema will match your old database schema (including index and key names) - you may run 'Initial' migration to empty (temporary) database and then copy __EFMigrationHistory table from there to your real database.
Otherwise, I recommend you create empty database using migration and use sql insert into ... select commands to copy data from your old database. Without this, you will receive exceptions when upgrading database later - for example changing index will lead to DropIndex and CreateIndex migration commands, and DropIndex will fail because there is no index with this name (index exist with other, pre-EF7 name).
In my projects - old (from EF6) and new database schemes are different, and I used second option.

EF6 + Postgres relation dbo.AspNetUsers does not exist

I have been following this post on using PostgreSQL with EF6 http://www.jasoncavett.com/blog/postgresql-and-entity-framework-6-code-first/.
I have started a brand new MVC5 project hoping to use Postgres in my application for backend. The application starts up fine however when you go to register a user (I selected individual authentication) I get the following error messsage
ERROR: 42P01: relation "public.AspNetUsers" does not exist
I am unsure as to how to resolve this problem.
The error happens on line 155 which can be seen here
More information can be provided if needed.
I had ran the application before migrating to Postgres so all I needed to was to add a migration and update database through the package manager console.
If you see this Error in 2018, the answer is because the table has not being added to the migrations.
dotnet ef migrations add 01_users &&
dotnet ef database update
It is interesting but when i write as below it works on tableplus;
select *
from "AspNetUsers";
or
select "UserName"
from "AspNetUsers";

moving to a new database with Code First Migrations

I have recently started using code first and migrations and I'm pretty happy with it.. I have been following the constant pattern of add-migration and update-database!
I have just tried to move from localdb to SQL Express and im having a real pain..
when I try and run the application.. I get the follow error..
Cannot find the object "dbo.AspNetUsers" because it does not exist or you do not have permissions.
In my Global file I have..
Database.SetInitializer(new MigrateDatabaseToLatestVersion());
Any ideas? It looks like the core forms tables are not being created?
if I run my application without the Initializer in the global file I get this.
Migrations is enabled for context 'ApplicationDbContext' but the database does not exist or contains no mapped tables. Use Migrations to create the database and its tables, for example by running the 'Update-Database' command from the Package Manager Console.
Thanks
Ste.

Why does Entity give me an "SSDL fragment is required" statement with a remote DB, but not SQL Express?

Similar to this question, I am trying to run an Entity CodeFirst project. I'm using the CreateDatabaseIfNotExists initializer. I am a sysadmin on the box the connect string points to.
If I change (or remove) the connection string, Entity will create the database on my local SQLExpress instance. Why won't it create the database on my remote instance? And, furthermore, why does it seem to require an artifact of data-first? This is a brand new project that is using nothing but code-first.
Using EF4.2. Remote machine is SQL2k8.

entity framework 4.1 code first CREATE DATABASE permission denied in database 'master'

I have created a generic repository project using Entity Framework 4.1 and it works great with my projects when added as an existing project to them but it doesn't work on them when just referenced as dll.
I get this error
CREATE DATABASE permission denied in database 'master'.
but I have added app.config file and set relevant connection string to my SQL Server 2005 database (I have used DbContext as type my context)
Please help me.
Here is my connection string :
<configuration>
<connectionStrings>
<add name="TasksEntities"
connectionString="server=(local); database=Tasks; trusted_connection=false; User=sa; Password=****; Persist Security Info=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
I just ran into this myself. The connection string name must match the class name of your DbContext subclass exactly. If it doesn't EF will not find the connection string and will try and fall back to doing something else (SQL embedded?) which doesn't work on my machine (I have full SQL Server installed).
You must verify where is configured your connectionstring if you are working with more than one project for example. If your startup project in your solution has a connectionstring configured and in Package Manager Console is pointing to the project with EF Migrations configured as well (in "Default Project").
You can run with the command in Package Manager Update-Database -Verbose what is the startup project and source migration or specify putting the parameters in the command:
Update-Database -SourceMigration MvProject.Data -StartUpProjectName MyProject.Web -Verbose
Seems like your credentials in the connection string should have permission to create database on your server. Log in to your database server and check whether your user account has the correct permissions. This will be a http://www.sqlservercurry.com/2008/04/resolving-create-database-permission.html