在 ASP.NET 核心 MVC 中使用 select 查询时出现 InvalidOperationException

InvalidOperationException when using select query in ASP.NET Core MVC

我正在创建一个 table,它将显示我的 SQL 数据库中的某些列。我收到错误

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List, but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable

我已尝试 运行 原始 sql 查询(使用 .FromSqlRaw),但在我看来 returns 模型值为空。我了解该错误,无法将我的查询设置为列表并返回 IEnumerable,但我在网上找不到成功。请让我知道我可以改进什么。谢谢!

我的观点

@model IEnumerable<MyApp.Models.BookModel>
            <table>
                <thead>
                    <tr>
                        <th>
                            @Html.DisplayNameFor(model => model.BookName)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => model.Author)
                        </th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var item in Model)
                    {
                        <tr>
                            <td>
                                @Html.DisplayFor(modelItem => item.BookName)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.Author)
                            </td>
                        </tr>
                    }
                </tbody>
            </table>

我的控制器

        [HttpGet("[action]")]
        [Route("/Books/Index")]
        public async Task<IActionResult> Index()
        {
            try
            {
                var data = _context.BookModel
                    .Where(x => x.Id == 10)
                    .Select(x => new { x.BookName, x.Author })
                    .AsNoTracking()
                    .ToListAsync();

                return View(await data);
            }
            catch (Exception)
            {

                throw;
            }
        }

附注:设置 id = 10 用于测试目的。

您可以发送 MyApp.Models.BookModel 的列表,将查询更改为:

var data = _context.BookModel
    .Where(x => x.Id == 10)
    .Select(x => new BookModel { BookName = x.BookName, Author = x.Author })
    .AsNoTracking()
    .ToListAsync();

var data = _context.BookModel
    .Where(x => x.Id == 10)
    .Select(x => new { x.BookName, x.Author })
    .AsNoTracking()
    .Select(x => new BookModel { BookName = x.BookName, Author = x.Author })
    .ToListAsync();

希望对您有所帮助。