Entity framework core V7.0.5 problem with generated code produce Invalid Opeeration Exception

Boucourt 105 Reputation points
2023-04-18T03:09:03.7433333+00:00

I generate a controller in visual studio 2022 with the template Add API Controller with actions, using Entity Framework> The assistant generate

	public class CitiesController : Controller
    {
        private readonly ApplicationDbContext _context;

        public CitiesController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: Cities
        public async Task<IActionResult> Index()
        {
			//return (IActionResult)await _context.Cities.ToListAsync();

			var applicationDbContext = _context.Cities.Include(c => c.Country);
			return View(await applicationDbContext.ToListAsync());
		}

I had to add

	[Route("api/[controller]/[action]")]
	[ApiController]

so that my HTTP request reach the action Index() The program halt with User's image

I put a breakpoint on that line and applicationDbContext contain the required data fetch from the DataBase. User's image

This code has been generated by the template What did I miss Any idea how to make it work

Developer technologies | .NET | Entity Framework Core
Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | ASP.NET | ASP.NET API
0 comments No comments
{count} votes

Answer accepted by question author
  1. Anonymous
    2023-04-18T06:18:04.0333333+00:00

    Hi,@Boucourt I reproduced the error,it has no relationship with EFCore: thumbnail_image (3)

    I think you've got mixed WebApi app with MVC app ,If you want to retrun ViewResult with return View() You should try with a MVC app

    4.18.1

    If you just want add a scaffolded api controller in Webapi project,please try with the following options:

    4.18.2

    and the error indicates lacking required service for MVC parttern,if you insist on mixing webapi with mvc,you have to call builder.Services.AddControllersWithViews(); to regist required service in Program.cs


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best regards,
    RuikaiFeng


1 additional answer

Sort by: Most helpful
  1. Boucourt 105 Reputation points
    2023-04-20T10:19:42.4033333+00:00

    I found the solution Adding builder.Services.AddMvc(); in program.cs injects dependencies needed by the framework, Thank to Camilo Terevinto

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.