开发者

Method cannot be translated into a store expression but it's body could

I have a class method

public partial class User
{
    public I开发者_StackOverflowEnumerable<Event> GetLikedEvents()
    {
        return this.Operations.Where(o => o.typeId == 
            Consts.MarkAsLikedOperationTypeId).Select(o => o.Event);
    }
}

and evaluating of an expression

IQueryable<User> users = repository.GetUsers().
    Where(u => u.GetLikedEvents().Any(e => e.id == likedEventId));

throws exception LINQ to Entities does not recognize the method GetLikedEvents() method, and this method cannot be translated into a store expression.

But if I copy body of the method to the expression like this

IQueryable<User> users = repository.GetUsers().
    Where(u => u.Operations.
            Where(o => o.typeId == Consts.MarkAsLikedOperationTypeId).
            Select(o => o.Event).
            Any(e => e.id == likedEventId));

it's translated without errors.

So I am interested how could I avoid code duplication if I am going to make different liked events checks in several places?


The block you copied from the method is not the same as the method. There is a big difference because your method runs as linq-to-objects on already loaded operations whereas your second query runs as linq-to-entities in the database. Try to rewrite the method this way:

public static IQueryable<Event> GetLikedEvents(this IQueryable<Operation> query, int typeId)
{
    return query.Where(o => o.typeId == typeId).Select(o => o.Event);
}

And your main query as:

IQueryable<User> users = repository.GetUsers()
    .Where(u => u.Operations.GetLindedEvents(Consts.MarkAsLikedOperationTypeId)
                            .Any(e => e.id == likedEventId));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜