(LocalDB) Update-Database Post-Error Error - "Can not attach the file ..."

0

I'm trying to use Sql Serves LocalDB in an application with the Entity Framework and Migrations, but when I give the Update-Database command, the following error occurs:

  

Can not attach the file   'C: \ Directories \ 9-ProjectsMVS \ DB Test \ DB Test \ bin \ Debug \ TestDB.mdf'   the database 'TestDB'.

I've tried:

  

sqllocaldb.exe stop MSSqlLocalDb

     

sqllocaldb.exe delete MSSqlLocalDb

And it did not solve ...: /

This is my Context:

using System.Data.Entity;
using TesteDeDB.Entidades;

namespace TesteDeDB.Contexto
{
    class ClasseContexto : DbContext
    {
        public ClasseContexto()
            : base("name=Model1")
        {
        }

        public DbSet<Cliente> clientes { get; set; }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
        }
    }
}

This is the Migrations configuration class:

namespace TesteDeDB.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<Contexto.ClasseContexto>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(Contexto.ClasseContexto context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data.
        }
    }
}

And this is the entity I'm trying to create in BD:

namespace TesteDeDB.Entidades
{
    public class Cliente
    {
        public int clienteID { get; set; }
        public string nome { get; set; }
        public string email { get; set; }
    }
}

And this is my connection String:

<connectionStrings>
    <add name="Model1" connectionString="data source=(LocalDb)\MSSQLLocalDb;attachdbfilename=|DataDirectory|\TesteDB.mdf;initial catalog=TesteDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
  </connectionStrings>
    
asked by anonymous 06.08.2018 / 19:08

1 answer

2

The problem is in your connection string. This part:

attachdbfilename=|DataDirectory|\TesteDB.mdf tells the bank that it should attach the "TestDB.mdf" file that is in the "DataDirectory".

If the database already exists and is attached, you need to remove this part of the connection string:

<add name="Model1" connectionString="data source=(LocalDb)\MSSQLLocalDb;initial catalog=TesteDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />

In addition, you may have to put the version of sql if it does not work, like this: Server=(localdb)\v12.0; . This is because you are using the 2014 version, so the 2012 version is "V11.0," and so on: #

    
06.08.2018 / 19:39