【问题标题】:InvalidOperationException: The entity type 'PassengerViewModel' was not found. Ensure that the entity type has been added to the modelInvalidOperationException:找不到实体类型“PassengerViewModel”。确保实体类型已添加到模型中
【发布时间】:2020-01-05 22:17:43
【问题描述】:

所以我试图让我的 MVC 网站直接使用 ViewModels 而不是数据。

正如标题所说,我遇到了一个异常,这是在我按下创建按钮添加新数据后发生的。

我会列出我现在正在使用的代码的 sn-ps。

这是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);
}

创建页面是 Visual Studio 为我创建的正常创建页面。我对其所做的唯一更改是不使用模型数据。该模型指的是我的 ViewModel。

然后在迁移类中。代码是这样的:

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);
                });

任何帮助或指导将不胜感激。

【问题讨论】:

    标签: c# asp.net-core asp.net-core-mvc viewmodel


    【解决方案1】:

    创建实体实例,复制模型值,然后将其(实体)添加到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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多