InvalidOperationException:传递到 ViewDataDictionary 的模型项是 Dbset[*] 类型,但此 ViewDataDictionary 是 [*] 类型

InvalidOperationException: The model item passed into the ViewDataDictionary is of type Dbset[*] but this ViewDataDictionary of type [*]

我只是无法理解我已经尽力了所以我希望你们能帮助我。 错误信息:

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1[BookStore1.Models.Book]', but this ViewDataDictionary instance requires a model item of type 'BookStore1.Models.Account'.

这就像一个在线书店,我正在尝试执行一个操作,您可以通过该操作显示数据库中的所有书籍并以管理员身份编辑它们。 那是我的书本模型:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace BookStore1.Models
{
    public class Book
    {
        [Key]
        public int Id { get; set; }
        [Required]
        public string? Name { get; set; }
        [Required]
        public string? Author { get; set; } = "Unknown";
        [Required]
        public int Price { get; set; }
        [NotMapped]
        public IFormFile? Image { set; get; }
    }
}

这是我的管理控制器:

using BookStore1.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using BookStore1.Models;

namespace BookStore1.Controllers
{
    [Authorize(Policy = "HasToBeAdmin")]
    public class AdminController : Controller
    {
        private readonly AppDataContext _database;
        private readonly IWebHostEnvironment _webHostEnvironment;
        public AdminController(AppDataContext database, IWebHostEnvironment webHostEnvironment)
        {
            _database = database;
            _webHostEnvironment = webHostEnvironment;
        }
        public IActionResult ShowBooks()
        {
            var books = _database.Books;
            return View(books);
        }
        [HttpGet]
        public IActionResult AddBook()
        {
            return View();
        }
        public async Task<IActionResult> AddBook(Book book)
        {
            if (ModelState.IsValid)
            {
                string wwwRootPath = _webHostEnvironment.WebRootPath;
                string fileName = Path.GetFileNameWithoutExtension(book.Image.FileName);
                string extention = Path.GetExtension(book.Image.FileName);
                string path = Path.Combine(wwwRootPath + "/booksImages", fileName);
                using (var fileStream = new FileStream(path, FileMode.Create))
                {
                    await book.Image.CopyToAsync(fileStream);
                }
                _database.Books.Add(book);
                _database.SaveChanges();
                return RedirectToAction("ShowBooks", "Admin");

            }
            return View(book);
        }
    }
}

不会查看的视图:

@model IEnumerable<BookStore1.Models.Book>

@{
    ViewData["Title"] = "ShowBooks";
}

<h1>ShowBooks</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Author)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Price)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Author)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Price)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

数据库上下文:

using Microsoft.EntityFrameworkCore;
using BookStore1.Models;

namespace BookStore1.Data
{
    public class AppDataContext: DbContext
    {
        public AppDataContext(DbContextOptions<AppDataContext> options): base(options)
        {
        }
        public DbSet<Account> Accounts { get; set; }
        public DbSet<Book> Books { get; set; }
    }
}

感谢您的宝贵时间和帮助。

您必须修复操作,将 dbset 转换为列表并将视图的名称添加到操作中(如果名称不是“ShowBooks.cshtml”

public IActionResult ShowBooks()
{
     var books = _database.Books.ToList();
     return View("viewName", books);
}

如果你上面显示的视图是ShowBooks.You只需要使用_database.Books.ToList()Serge所说。 您在视图中使用 @model IEnumerable<BookStore1.Models.Book>,并将 System.Collections.Generic.List1[BookStore1.Models.Book]` 传递给视图,这是正确的。

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List`1[BookStore1.Models.Book]', but this ViewDataDictionary instance requires a model item of type 'BookStore1.Models.Account'.

对于错误,视图将包含 @model BookStore1.Models.Account。您需要找到包含它的视图,并检查从操作传递的数据。