[英]Entity Framework Core: How to perform a Join on `IQueryable` by selecting only the latest created records?
I am refactoring a code in production which create duplicates: 我正在重构生产中重复的代码:
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
};
The _context.Audits
actually records (use-triggered) changes that happen for certain records in _context.Cashout
. _context.Audits
实际上在_context.Cashout
记录了某些记录发生的(使用触发)更改。
I am looking for a clean way to fix the current behavior of the join
by selecting only (for a given EntityId
) the latest audit record. 我要寻找一个干净的方式来解决的当前行为join
只选择(对于给定EntityId
)最新的审计记录。
The code you currently have is essentially doing a LEFT OUTER JOIN
which gets all the Cashouts records and the corresponding audit record. 您当前拥有的代码实际上是在做一个LEFT OUTER JOIN
,它获取所有Cashouts记录和相应的审计记录。
Assuming you have a timestamp column (say CreatedOn ) in the Audits
table which captures when that audit record was created, you could use a GROUP JOIN here like so - 假设您在“ 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.