[英]Entity Framework Core: How to perform a Join on `IQueryable` by selecting only the latest created records?
我正在重構生產中重復的代碼:
private IQueryable<CashoutModel> GetCashoutModels() =>
from cashout in _context.Cashouts
join audit in _context.Audits
on cashout.Id.ToString() equals audit.EntityId
into cashoutModel
from audit in cashoutModel.DefaultIfEmpty()
orderby cashout.CreatedOn descending
select new CashoutModel
{
Id = cashout.Id,
Amount = cashout.Amount,
Comment = cashout.Comment,
CreatedOn = cashout.CreatedOn,
RecipientAccountId = cashout.RecipientAccountId,
RecipientAccountName = cashout.RecipientAccountName,
State = cashout.State,
Reason = cashout.Reason,
CreatedBy = audit == null
? null
: audit.Name
};
_context.Audits
實際上在_context.Cashout
記錄了某些記錄發生的(使用觸發)更改。
我要尋找一個干凈的方式來解決的當前行為join
只選擇(對於給定EntityId
)最新的審計記錄。
您當前擁有的代碼實際上是在做一個LEFT OUTER JOIN
,它獲取所有Cashouts記錄和相應的審計記錄。
假設您在“ Audits
表中有一個時間戳列(例如CreatedOn )捕獲創建該審計記錄的時間,則可以在此處使用GROUP JOIN ,如下所示:
private IQueryable<CashoutModel> GetCashoutModels() =>
_context.Cashouts.GroupJoin(_context.Audits,
c => c.Id.ToString(),
a => a.EntityId,
(cashout, audit) => new CashoutModel
{
Id = cashout.Id,
Amount = cashout.Amount,
Comment = cashout.Comment,
CreatedOn = cashout.CreatedOn,
RecipientAccountId = cashout.RecipientAccountId,
RecipientAccountName = cashout.RecipientAccountName,
State = cashout.State,
Reason = cashout.Reason,
CreatedBy = audit.OrderByDescending(x => x.CreatedOn)
.Select(y => y.Name)
.FirstOrDefault()
}).AsQueryable();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.