I am creating an application with .net core 6, but I have an error when performing the query, the first thing I did was connect to the database created with SQL Server, install the packages:
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
- Create the Models folder
Since I will be using an existing database I opened the NuGet package manager console, and proceeded with the following command:
Scaffold-DbContext “Server=xxxxx;Database=xxxx;User ID=xxxx;Password=xxxxx” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
I then opened the File containing the context, and proceeded to send my connection string to the appsettings.json file , leaving it as follows:
{
"ConnectionStrings": {
"ConexionBD": "Server=xxxxx;Database=Cotizador;User ID=xxxx;Password=xxxxx"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
And since I'm working with .Net version 6, I've added the following lines of code in Program.cs , in order to keep the connection string out of the DBContext file, being like this:
builder.Services.AddDbContext<CotizadorContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("ConexionBD"));
});
From there add a blank MVC Controller in the Controllers folder, and add the following code:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using CotizadorV3.Models;
using CotizadorV3.Clases;
namespace CotizadorV3.Controllers
{
public class ClientesController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpGet]
[Route("api/Clientes/listaClientes")]
public IEnumerable<ClienteCLS> listaClientes()
{
using (CotizadorContext bd = new CotizadorContext())
{
List<ClienteCLS> clientes = (from c in bd.Clientes
select new ClienteCLS
{
NombreCliente = c.NombreCliente,
}).ToList();
return clientes;
}
}
}
}
And put https://localhost:44458/api/listaClientes
in Postmat I get error 404
And I don't know what's wrong, since in 3.1 it works fine, performing these processes.
Update:
I made use of this command, Add-Migration "Version 1.1"
and if it connects and generates it without any problem.