问题描述
我有一个实体集,该实体集包含带有包含ID(GUID)和CreatedAt(DateTime)的复合键的实体.此CreatedAt是创建实体时的时间.每个记录代表每个实体的每个版本,以便多个记录可以具有相同的ID.
I have an Entity set that has Entities with a compound key containing ID (GUID) and CreatedAt (DateTime). This CreatedAt is when the entity was created. Each record represents each version of each entity such that muliple records can have the same ID.
我想创建一个IQueryable-returning方法,该方法可以重复使用,以便仅返回所请求实体的最新版本,但是我一直在努力寻找答案(如果确实存在答案) ).
I want to create an IQueryable-returning method that I can re-use such that it will only return the latest version of the entity requested, but I'm struggling to find the answer (if, indeed, there is an answer).
我知道我可以写一个查询,例如
I know that I can write a query such as
(from e in context.Entities where e.ID = myID orderby e.CreatedAt).FirstOrDefault();
但是我希望能够做到这一点:
But I want to be able to do this instead:
(from e in context.GetCurrentEntities() where e.ID = myID).FirstOrDefault();
这样只会返回所需实体的最新版本.
Such that it will only return the latest versions of the entity required.
这可行吗?
非常感谢您的帮助.
李
推荐答案
如果按ID分组,则可以使用以下方法从每个组中选择最新的分组:
If you group by ID, you can select only the most recent from each group using something like this:
public IQueryable<Entity> GetCurrentEntities()
{
return from e in this.Entities
group e by e.ID into g
select g.OrderByDescending(e => e.CreatedAt).First();
}
您不需要FirstOrDefault()
,因为除非该组中至少有一个Entity
,否则不会创建一个组.
You don't need FirstOrDefault()
because a group won't be created unless there's at least one Entity
in the group.
这篇关于实体框架创建最新的IQueryable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!