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; }
}
}
There is no way to convert your code-first classes into database-first classes. Creating the model from the database will create a whole new set of classes, regardless of the presence of your code-first classes. However, you might not want to delete your code-first classes right away.
Versioning databases is hard, but with code first and code first migrations, it's much more effective. Because your database schema is fully based on your code models, by version controlling your source code you're helping to version your database.
This step-by-step walkthrough provides an introduction to Code First development targeting an existing database. Code First allows you to define your model using C# or VB.Net classes. Optionally additional configuration can be performed using attributes on your classes and properties or by using a fluent API.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With