我有一个主VendorProfile表和一个包含状态代码和日期戳的1-VendorHistory表。以下查询仅用于检索每个供应商的最新状态(状态代码和日期)。但是,我还想做的是将状态代码转换为状态名称,该名称位于StatusCodes查找表中。
public IEnumerable<BrowseStatusModel> BrowseByStatus()
{
IQueryable<BrowseStatusModel> viewModel = _db.VendorProfiles
.Include("VendorStatusHistory")
.Include("StatusCodes")
.Select(s => new BrowseStatusModel
{
ProfileID = s.ProfileID,
Name = s.Name,
CompanyName = s.CompanyName,
DateCreated = s.DateCreated,
Status = s.VendorStatusHistories.OrderByDescending(o => o.DateCreated).FirstOrDefault().Status,
StatusDate = s.VendorStatusHistories.OrderByDescending(o => o.DateCreated).FirstOrDefault().DateCreated,
StatusName = ???
})
.OrderBy(x => x.ProfileID);
return viewModel;
}
作为奖励跟进,我想知道如何修改上述查询,只返回VendorHistory表中匹配行的供应商 - 排除没有历史记录的记录。
答案 0 :(得分:1)
您可以先选择最后一个VendorStatusHistory
,然后选择其属性:
_db.VendorProfiles
.Select(s => new {
Profile = s,
LastHist = s.VendorStatusHistories
.OrderByDescending(o => o.DateCreated)
.FirstOrDefault()
})
.Select(x => new BrowseStatusModel
{
ProfileID = x.Profile.ProfileID,
Name = x.Profile.Name,
CompanyName = x.Profile.CompanyName,
DateCreated = x.Profile.DateCreated,
Status = x.LastHist.Status,
StatusDate = x.LastHist.DateCreated,
StatusName = x.LastHist.StatusCOde.StatusName
})
.OrderBy(x => x.ProfileID);