peter
peter

Reputation: 2103

LINQ & class method

How can I call a method in a class and use that for my selection in LINQ? Well.. this is what I mean: My class "Law" keeps a list of Versions and offers a method to get the current version:

public class Law
{   
    ...
    public virtual IList<LawVersion> Versions {get; set;}

    public LawVersion CurrentVersion()
    {
        // Given a list of Laws, how can I use this method in my selection clause?
        return Versions.OrderByDescending(x => x.CreationDate).First();
    }
}

I would like to obtain a List of all current LawVersions. I have tried like this:

Context.Laws.Select(x => x.CurrentVersion())

which ends in

"LINQ to Entities does not recognize the method.. cannot be translated into a store expression"

Upvotes: 0

Views: 50

Answers (1)

CodeCaster
CodeCaster

Reputation: 151594

This happens because Context.Laws is an interface to your database, where every IQueryable operation you perform on it will be translated by Entity Framework into a query. Like your Select() call. But it can't translate your C# method to a query, so it throws.

You need to materialize the list first, for example by calling .ToList(), then call your method on that list:

Context.Laws.ToList().Select(x => x.CurrentVersion())

Upvotes: 2

Related Questions