dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.65k stars 3.15k forks source link

MVC Exception trough cli dotnet asp-codegenerator #15010

Closed dieruiqu closed 1 year ago

dieruiqu commented 5 years ago

Hi! I'm having troubles to lunch my web service in local host. All code has been builded with CLI and powershell with dotnet asp-codegenerator. This is the error message that shows in the explorer (Google Chrome or IE, both):

`An unhandled exception occurred while processing the request.

InvalidOperationException: Unable to resolve service for type 'seguridaddeTelefonia.Models.pruebas_telfContext' while attempting to activate 'seguridaddeTelefonia.Controllers.EstadoLineasController'.

Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired) Stack Query Cookies Headers

InvalidOperationException: Unable to resolve service for type 'seguridaddeTelefonia.Models.pruebas_telfContext' while attempting to activate 'seguridaddeTelefonia.Controllers.EstadoLineasController'.

Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

lambda_method(Closure , IServiceProvider , object[] )

Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider+<>c__DisplayClass4_0.b__0(ControllerContext controllerContext)

Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider+<>c__DisplayClass5_0.g__CreateController|0(ControllerContext controllerContext)

Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)

Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()

Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()

Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)

Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)

Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()

Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()

Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)

Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)

Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Show raw exception details `

My Powershell escript to create the models, views and controller:

`dotnet ef dbcontext scaffold "Server=$Server;Database=$DB;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models

dotnet aspnet-codegenerator controller -name EstadoLineasController -actions -outDir Controllers -m Lineas -dc pruebas_telfContext

dotnet aspnet-codegenerator view EstadoLineas Create -outDir Views -udl -m Lineas -namespace EstadoLineasController `

This is my dependency relation: dotnet add $csproj_name package Microsoft.AspNetCore.Razor.Language -v 2.2.0 dotnet add $csproj_name package Microsoft.Extensions.DependencyInjection -v 2.2.0 dotnet add $csproj_name package Microsoft.Extensions.DependencyInjection.Abstractions -v 2.2.0 dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design -v 2.1.1 dotnet add package Microsoft.EntityFrameworkCore.SqlServer -v 2.1.1" dotnet add package Microsoft.EntityFrameworkCore.Tools -v 2.1.1" dotnet add package Microsoft.EntityFrameworkCore.SqlServer.Design -v 2.0.0" dotnet add package Microsoft.EntityFrameworkCore.Relational -v 2.1.1" dotnet add package Microsoft.EntityFrameworkCore.InMemory -v 2.1.1

I know that dotnet core warning to set a version lesss than 2.2.0 by the other way, alert an error and not creates the generators.

The code generated in .cs:

Controller: `using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using seguridaddeTelefonia.Models;

namespace seguridaddeTelefonia.Controllers { public class EstadoLineasController : Controller { private readonly pruebas_telfContext _context;

    public EstadoLineasController(pruebas_telfContext context)
    {
        _context = context;
    }

    // GET: EstadoLineas
    public async Task<IActionResult> Index()
    {
        return View(await _context.Lineas.ToListAsync());
    }

    // GET: EstadoLineas/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var lineas = await _context.Lineas
            .FirstOrDefaultAsync(m => m.Numero == id);
        if (lineas == null)
        {
            return NotFound();
        }

        return View(lineas);
    }

    // GET: EstadoLineas/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: EstadoLineas/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Numero,Extension,FechaAlta,FechaBaja,Nombre,UneArea,Icc,Sociedades,CentroDeCoste,Tarifa,Puk,Pin,Estado,Operador,Observaciones,Portabilidad,F18,F19")] Lineas lineas)
    {
        if (ModelState.IsValid)
        {
            _context.Add(lineas);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(lineas);
    }

    // GET: EstadoLineas/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var lineas = await _context.Lineas.FindAsync(id);
        if (lineas == null)
        {
            return NotFound();
        }
        return View(lineas);
    }

    // POST: EstadoLineas/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("Numero,Extension,FechaAlta,FechaBaja,Nombre,UneArea,Icc,Sociedades,CentroDeCoste,Tarifa,Puk,Pin,Estado,Operador,Observaciones,Portabilidad,F18,F19")] Lineas lineas)
    {
        if (id != lineas.Numero)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(lineas);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!LineasExists(lineas.Numero))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(lineas);
    }

    // GET: EstadoLineas/Delete/5
    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var lineas = await _context.Lineas
            .FirstOrDefaultAsync(m => m.Numero == id);
        if (lineas == null)
        {
            return NotFound();
        }

        return View(lineas);
    }

    // POST: EstadoLineas/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        var lineas = await _context.Lineas.FindAsync(id);
        _context.Lineas.Remove(lineas);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    private bool LineasExists(int id)
    {
        return _context.Lineas.Any(e => e.Numero == id);
    }
}

} `

and the startup.cs `using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection;

namespace seguridaddeTelefonia { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

} `

Thanks in advance!!!

P.D: Curiosly, when i'm created the app with VS2017, not dotnet console, the app runs fine but not with cli dotnet console... ughhhhh. I need to automathize a the creation of a lot of forms in web.

dieruiqu commented 5 years ago

Finally I found a solution, later i will post!!