实体框架创建最新的IQuerable [英] Entity Framework creating IQuerable of the most recent

查看:186
本文介绍了实体框架创建最新的IQuerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体集,其实体具有包含ID(GUID)和CreatedAt(DateTime)的复合键。此CreatedAt是创建实体的时间。每个记录表示每个实体的每个版本,以便多个记录可以具有相同的ID。



我想创建一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆