views:

87

answers:

3

Hi

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

A: 

I think you are looking at a smaller picture. Have you considered implementing repository pattern?LINK otherwise looking at your requirements you will need to add this GetCurrentEntities method to your context class.

Perpetualcoder
Hi PerpetualcoderThanks for the advice. We've spent a lot of time looking at how to continue with EF in our current project. I found EF gets in the way too much. After looking at the options (other ORMs, hand-coded DALs), we are reigning in EF and use it as 'type-safe' SQL and avoid all it's other 'features'.What advantages does the Repostiory Pattern give here? You are correct that my intention is to add the GetCurrentEntities() to the DataContext.
Lee Atkinson
The repository pattern makes it trivial to swap out the EF for a mock repository when you unit test your controllers.
Craig Stuntz
+2  A: 

How about:

public partial class MyEntities // or whatever you call your ObjectContext
{
    public IQueryable<Entity> GetCurrentEntities()
    {
        return from e in context.Entities 
               group e by e.ID into g
               from ge in g
               orderby ge.CreatedAt desc
               select ge.First();
    }
}

This is off the top of my head, but it should get you started.

Craig Stuntz
Thanks - is this equivalent to dahlbyk's solution, or is there a differnt result?
Lee Atkinson
They are equivalent.
dahlbyk
Great - thanks once again!
Lee Atkinson
+2  A: 

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.

dahlbyk
Thanks - I'll give it a go
Lee Atkinson