I can’t connect localDB with visual studio

Asked

Viewed 3,848 times

2

I’m trying to use the Entity framework in Visual Studio, but when I try to run the program generates the error:

System.Data.SqlClient.SqlException was unhandled
  Class=20
  ErrorCode=-2146232060
  HResult=-2146232060
  LineNumber=0
  Message=A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Não é possível criar uma instância automática. Consulte o log de eventos do Aplicativo do Windows para obter detalhes do erro.
)
  Number=-1983577832
  Server=""
  Source=.Net SqlClient Data Provider
  State=0
  StackTrace:
       at CursoEntity.Program.Main(String[] args) in c:\users\almeijun\documents\visual studio 2015\Projects\CursoEntity\CursoEntity\Program.cs:line 29
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:    

The configuration of the App.config file for the connection is like this:

<connectionStrings>
    <add name="EntidadesContext" 
      connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\almeijun\documents\visual studio 2015\Projects\CursoEntity\CursoEntity\Loja.mdf;Integrated Security=True"
      providerName="System.Data.SqlClient" />
</connectionStrings>

The created classes are:

public class Usuario
{
    public int ID { get; set; }
    public string Nome { get; set; }
    public string Senha { get; set; }
}

public class EntidadesContext : DbContext
{
    public DbSet<Usuario> Usuarios { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        try
        {
            EntidadesContext contexto = new EntidadesContext();

            contexto.Database.CreateIfNotExists();

            Usuario usuario = new Usuario() { Nome = "Junior", Senha = "1234" };
            contexto.Usuarios.Add(usuario);

            contexto.SaveChanges();

            contexto.Dispose();

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

Thank you for your attention.

3 answers

2

change your config web to

 <connectionStrings>
  <add name="EntidadesContext" connectionString="Server=.\SQLEXPRESS;Database=SeuBanco;user id=sa;password=SuaSenha;multipleactiveresultsets=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

and its class to.

class Program
{
    static void Main(string[] args)
    {
        try
        {
            using (var DBCtx = new EntidadesContext())
            {
                DBCtx.Database.CreateIfNotExists();

                Usuario usuario = new Usuario() { Nome = "Junior", Senha = "1234" };
                DBCtx.Usuarios.Add(usuario);

                DBCtx.SaveChanges();    
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}
  • I wanted it to work with Localdb, but this solution solves my problem. Thank you very much.

2


I found the answer.

As I am using Localdb 20014 the configuration of the Connection string should be this:

<connectionStrings>
   <add name="EntidadesContext" connectionString="Data Source=    (LocalDB)\MSSQLLocalDB;AttachDbFilename=|path|\LojaEF.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

0

In my case this worked better, using "Datadirectory" in "Attachdbfilename":

<connectionStrings>
         <add name="DefaultConnection" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\NomeMeuDB.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.