Reputation: 6756
I get always this exception, even if Database initializer is set to CreateIfNotExists.
Additional information: Cannot create file 'C:\\Users\\Krab\\Documents\\Visual Studio 2013\\Projects\\Customer_UI\\customers2.mdf' because it already exists. Change the file path or the file name, and retry the operation.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
Why is EF trying to create the database even if it already exists?
App.config
<connectionStrings>
<add name="Customer.CustomersContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='C:\\Users\\Krab\\Documents\\Visual Studio 2013\\Projects\\Customer_UI\\customers2.mdf';Integrated Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
</connectionStrings>
DbContext:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
namespace Customer
{
public class CustomersContext : DbContext
{
public CustomersContext() : base("Customer.CustomersContext")
{
Database.SetInitializer(new CreateDatabaseIfNotExists<CustomersContext>());
//Database.CreateIfNotExists();
//System.Console.WriteLine(Database.Connection.ConnectionString);
}
public DbSet<CustomerDb> Customers { get; set; }
public DbSet<Contact> Contacts { get; set; }
}
}
Upvotes: 5
Views: 4425
Reputation: 4280
The error is referring to a file on the SQL Server instance, wherever that is. In my case, it was a different machine. I had renamed the database in hopes of getting EF to recreate it
Upvotes: 0
Reputation: 6756
Ok now it looks fine.
Upvotes: 1
Reputation: 14133
You don't have to escape backslashes in App.config files.
My guess is that whatever mechanism that checks for an existing database does not correctly resolve file paths with double directory separators (C:\\Users\\...)
.
EF would then go ahead and try to create a new database, but whatever mechanism that creates new databases does correctly resolve file paths with double directory separators. Resulting in an IOException
because the file exists.
If my hunch is correct, simply unescaping the path would have fixed the problem.
Upvotes: 4