floatingfrisbee
floatingfrisbee

Reputation: 938

Join using Linq failing with Entity Framework 4.0

I'm having trouble running a join linq query against EF 4.0. Below is the code, stripped of all unnecessary statements, still reproducing the error)

using (var threadRepo = new Repo<Thread>())
using (var postRepo = new Repo<Post>())
{
    var query = threadRepo
                    .Join(postRepo, t => t.PostId, s => s.Id, (t, s) => 1);

    var array = query.ToArray();
}

Repo is my implementation of the repository pattern, and the join method looks like this:

public IEnumerable<TResult> Join<TInner, TKey, TResult>(
        IEnumerable<TInner> inner,
        Expression<Func<TEntity, TKey>> outerSelector, 
        Expression<Func<TInner, TKey>> innerSelector, 
        Expression<Func<TEntity, TInner, TResult>> result)
{
    return _objectSet.Join(inner, outerSelector, innerSelector, result);
}

The error I get is

Unable to create a constant value of type 'Post'. 
Only primitive types ('such as Int32, String, and Guid') 
are supported in this context.

The same query works in LinqPad against the same database (though offcourse, there is not EF 4.0 there)

from t in Thread
join p in Post on t.PostId equals p.Id
select 1

Any clues on why Linq is giving me this exception?

Update

Based on a suggestion below, I tried using a common datacontext for both the repositories using a unit of work. However that doesn't seem to fix the issue. Below is the code I used

using (var uow = new UnitOfWork<CommunicationEntities>())
{
    using (var threadRepo = new Repo<Thread>(uow))
    using (var postRepo = new Repo<Post>(uow))
    {
        var query = threadRepo
                        .Join(postRepo, t => t.PostId, s => s.Id, (t, s) => 1);

        var array = query.ToArray();
    }
}

This gives me the same error as before.

Thanks Jaspreet

Upvotes: 0

Views: 416

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160992

A common mistake I have seen is that the data context is on the repository level and each repository uses a different data context - in this case that would explain the error. Instead your repositories all should share the same data context using the Unit of Work pattern.

Upvotes: 1

Related Questions