实体框架创建最新的IQuerable [英] Entity Framework creating IQuerable of the most recent
问题描述
我想创建一个IQuerable返回方法,我可以重复使用它只会返回所请求的实体的最新版本,但是我很难找到答案(如果确实有答案)。
我知道我可以编写一个查询,例如
(从e在context.Entities其中e.ID = myID order by e.CreatedAt)。 FirstOrDefault();
但是我想要这样做:
(从e在context.GetCurrentEntities()中e.ID = myID).FirstOrDefault();
这样它只会返回所需实体的最新版本。
这是否可行?
非常感谢您的帮助。
/ p>
如果您按ID分组,则可以使用以下方式仅选择每个组中的最新内容:
public IQueryable< Entity> GetCurrentEntities()
{
从e.Entities
中的e返回e.ID到g
中的e e选择g.OrderByDescending(e => e.CreatedAt).First ();
}
您不需要 FirstOrDefault()
,因为除非组内至少有一个 Entity
,否则不会创建一个组。
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.
I want to create an IQuerable-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.
Is this doable?
Many thanks for your help.
Lee
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();
}
You don't need FirstOrDefault()
because a group won't be created unless there's at least one Entity
in the group.
这篇关于实体框架创建最新的IQuerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!