【问题标题】:InvalidOperationException when using select query in ASP.NET Core MVC在 ASP.NET Core MVC 中使用选择查询时出现 InvalidOperationException
【发布时间】:2020-07-10 15:24:50
【问题描述】:

我正在创建一个表,它将显示我的 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),但在我看来它返回了一个空模型值。我了解该错误,并且无法将我的查询设置为列表并返回 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 用于测试目的。

【问题讨论】:

  • new { x.BookName, x.Author } 创建一个与BookModel 不同的新匿名类型。
  • @KirkLarkin 好的,很高兴知道,谢谢您的回复。你对如何修改我的代码有什么建议吗?

标签: linq asp.net-core model-view-controller linq-to-sql entity-framework-core


【解决方案1】:

您可以发送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();

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-04
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    相关资源
    最近更新 更多