Trying a CRUD with Asp.Net Core 3.1 and gives error in connection with Sql Server

Asked

Viewed 42 times

-2

This is my connection string

"ConnectionStrings": {
    "bdcoreconn": "Server=.\\SQLEXPRESS;Database=BdCoreCrud;Trusted_Connection=False;MultipleActiveResultSets=true;User Id=sa;Password=Simb@d123;"
  },

In Startup.Cs I have this:

 services.AddDbContext<CrudContext>(options =>
             options.UseSqlServer(Configuration.GetConnectionString("bdcoreconn")));

This is my Context:

public class CrudContext: DbContext
    {
        public CrudContext(DbContextOptions options) : base(options) { }
        public DbSet<Desenvolvedor> Desenvolvedores { get;set; }
        public DbSet<Projeto> Projetos { get; set; }
        public DbSet<LancamentoHoras> Lancamentos { get; set; }
        public DbSet<ProjetoDesenvolvedor> ProjetoDesenvolvedores { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Desenvolvedor>()
                .HasKey(p => p.IdDesenvolvedor);
            modelBuilder.Entity<LancamentoHoras>()
                .HasKey(p => p.IdLancamentoHoras);
            modelBuilder.Entity<Projeto>()
                .HasKey(p => p.IdProjeto);
            modelBuilder.Entity<ProjetoDesenvolvedor>()
                .HasKey(p => p.IdProjetoDesenvolvedor);
        }
    }

When I give one SaveChanges(), caught that mistake:

Microsoft.Data.Sqlclient.Sqlexception (0x80131904): 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: Named Pipes Provider, error: 40 - Could not open a Connection to SQL Server)

Someone knows how I fix it?

I changed in startup the way to get the connection string for this one

var connection = @"Server=DESKTOP-K4MI90D\\SQLEXPRESS;Initial Catalog=BdCoreCrud;Trusted_Connection=False;MultipleActiveResultSets=true;User Id=sa;Password=Simb@d123;";
            services.AddDbContext<CrudContext>(options => options.UseSqlServer(connection));

Note that in Swagger the error has changed. Such a

Error 500 Undocumented

And I don’t know what that is

inserir a descrição da imagem aqui

  • "Someone knows how I fix it?" is needed for a valid string and confirm that the database is responding with this setting. Already tried to connect with these Settings in Management Studio?

  • @Ricardopunctual, that’s how I connect. That last configuration was attempt. But the connection by Management is that way: DESKTOP-K4MI90D\SQLEXPRESS and other user and password. And yet I get the same error. I just haven’t restarted the machine yet.

  • these double bars can be a problem, already tried with .\SQLEXPRESS?

  • It does not accept simple bar. It gives error of face. I tried localhost and the same thing.

  • The basic error is: Could not open connection to sql server. Is there any other step I need to take?

  • @pnet You have already guaranteed that you have access to the base used in the string Connection, right?

  • @LINQ, yes. I use, because the tables in this database I created by management. I think there is a map or whatever.

  • I made an edit with a new way to get the connection string and the error message changed.

  • By all indications your connection string is still wrong or you have some Sqlexpress configuration problem on your machine

  • @Leandroangelo, what was wrong was Context. The method was not defined: protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) done it worked. I thank everyone there.

Show 5 more comments

1 answer

0

Initially you must be your connection:

"ConnectionStrings": {
    "DefaultConnection": "Server=DESKTOP-N8415MR\\SQLEXPRESS;Database=BdCoreCrud;User Id=sa;Password=Simb@d123;"
  },


 services.AddDbContext<CrudContext>(options =>
     options.UseSqlServer(
        Configuration.GetConnectionString("DefaultConnection")));

Your Onmodelcreating and where are the mappings, the ideal would be you do this way, makes the creation of a folder for class mapping only

   protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            base.OnModelCreating(modelBuilder);

            modelBuilder.ApplyConfiguration(new UsuarioMapping());//ok

            //evitar a deleção em cascade
            foreach (var foreignKey in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
            {
                foreignKey.DeleteBehavior = DeleteBehavior.Restrict;
            }

        }

Example of mapping:

 public class UsuarioMapping : IEntityTypeConfiguration<Usuario>
    {
        public void Configure(EntityTypeBuilder<Usuario> builder)
        {
            builder.HasKey(p => p.Id);
            builder.Property(p => p.NomeCompleto).IsRequired().HasColumnType("varchar(100)");
            builder.Property(p => p.Imagem).HasColumnType("varchar(100)");
            builder.Property(e => e.CentroDeCusto).HasMaxLength(50).IsUnicode(false);
            builder.Property(e => e.CodigoUsuario).HasMaxLength(10).IsUnicode(false).IsFixedLength();


            builder.Property(e => e.Ativo).HasMaxLength(1).IsUnicode(false);
            builder.Property(e => e.DataCadastro).HasColumnType("datetime");
            builder.Property(e => e.DataAlteracao).HasColumnType("datetime");


            builder.HasOne(d => d.Empresa)
                .WithMany(p => p.Usuario)
                .HasForeignKey(d => d.IdEmpresa);

            builder.HasOne(d => d.Funcao)
                .WithMany(p => p.Usuario)
                .HasForeignKey(d => d.IdFuncao);

            builder.HasOne(d => d.Departamento)
                .WithMany(p => p.Usuario)
                .HasForeignKey(d => d.IdDepartamento);


            builder.ToTable("Usuario");
        }

    }

Browser other questions tagged

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