【发布时间】:2020-09-12 19:43:52
【问题描述】:
我有一个包含一系列通知的数据库表。同一个城市可以有多个通知,xgrid 和 ygrid。因此,我通过 SQL Lite 查询获取最新日期并使用该记录。
在阅读了本网站上的几篇文章后,我尝试将模型查询拼凑起来,相当于下面的 SQL Lite 查询。
问题是模型查询没有编译错误,但结果为空。
SQL Lite 查询
select * from (
select
NOTIFY_ID,
NOTIFICATION_DATE,
CITY_NAME,
ITEM_X_GRID,
ITEM_Y_GRID,
GRID_QUANTITY,
row_number() over(partition by ITEM_X_GRID, ITEM_Y_GRID, CITY_NAME order by NOTIFICATION_DATE desc) as rn
from
USER_ILLY_DATA
) t
where t.rn = 1
order by CITY_NAME
类和列表
public class MostRecentNotify
{
public int RecordID { get; set; }
public string ItemXGrid { get; set; }
public string ItemYGrid { get; set; }
public string GridQuantity { get; set; }
public string NotificationDate { get; set; }
public string CityName { get; set; }
public string IllyItemCode { get; set; }
}
public IList<MostRecentNotify> RecentNotifies { get; set; }
获取最新记录的模型查询(无效)
var tempResults = _context.IllyAPIData.GroupBy(i => new { i.ItemXGrid, i.ItemYGrid, i.CityName})
.Select(g => g.OrderByDescending(y => y.NotificationDate).FirstOrDefault());
模型查询将值传递给要在 Razor 页面中调用的类
var RecentNotifies = tempResults.Select(r => new MostRecentNotify//).ToListAsync();
{
ItemXGrid = r.ItemXGrid,
ItemYGrid = r.ItemYGrid,
GridQuantity = r.GridQuantity,
NotificationDate = r.NotificationDate,
CityName = r.CityName,
IllyItemCode = r.IllyriadCode,
RecordID = r.RecordID,
}).ToListAsync();
Razor 页面 sn-p
@foreach (var item in Model.RecentNotifies.Where(i => i.CityName == city.DistinctCityName)){
@foreach (var indRes in Model.RareResources.Where(r => r.ResourceCode == item.IllyItemCode)){
页面加载错误
ArgumentNullException: Value cannot be null. (Parameter 'source')
System.Linq.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
System.Linq.Enumerable.Where<TSource>(IEnumerable<TSource> source, Func<TSource, bool> predicate)
IllyriadAssist.Pages.harvestableInventory.Pages_harvestableInventory_Index.ExecuteAsync() in Index.cshtml
+ @foreach (var item in Model.RecentNotifies.Where(i => i.CityName == city.DistinctCityName)){
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
【问题讨论】:
-
什么是
Model.RecentNotifies?您似乎没有将结果分配给它(var RecentNotifies = …只是将查询结果分配给临时变量),因此它将是null。ToList()/ToListAsync()永远不会产生null。 -
@ivanStoev 也许我看错了,但我想既然我将
tempResults调用到RecentNotifies我会选择该查询中的所有结果到RecentNotifies并将它们分配到具有我想要的属性/结果的类。Model.RecentNotifies正在调用特定的模型 cs (harvestableInventory.cs) -@model IAssistApp.Pages.harvestableInventory.IndexModel- 这是数据库上下文和相关类/方法所在的位置。这就是为什么我相信第一个查询tempResults没有返回结果。断点显示RecentNotifiesnull
标签: c# asp.net-mvc sqlite entity-framework-core razor-pages