Search code examples
c#asp.net-coreasp.net-core-mvcviewmodel

InvalidOperationException: The entity type 'PassengerViewModel' was not found. Ensure that the entity type has been added to the model


So i am trying to make my MVC website to use ViewModels instead of the data directly.

As the title says i am getting an exception and this is happening after i press the create button to add new data.

Ill list the snippets of codes that i am using right now.

This is the create operation in the Controller

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Surname,FirstName,Email")] PassengerViewModel passenger)
{
    if (ModelState.IsValid)
    {
        _context.Add(passenger);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    return View(passenger);
}

The Create page is a normal create page that visual studio created for me. the only change i made to it is instead of using the model data. the model is referring to my ViewModel.

Then in the migration class. the code is this:

migrationBuilder.CreateTable(
                name: "Passengers",
                schema: "WebSite",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    Surname = table.Column<string>(nullable: false),
                    FirstName = table.Column<string>(nullable: false),
                    Email = table.Column<string>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Passengers", x => x.Id);
                });

Any help or guidance would be appreciated.


Solution

  • Create an instance of the entity, copy model values over, then add it (the entity) to the DbContext.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,Surname,FirstName,Email")] PassengerViewModel model)
    {
        if (ModelState.IsValid)
        {
            Passenger passenger = new Passenger
            {
                Id = model.Id,
                FirstName = model.FirstName,
                Email = model.Email
            };
            await _context.Passengers.AddAsync(passenger);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
    
        return View(passenger);
    }