9

I'm creating a delegate to retrieve all album records in the database. I've used this same way in another project, but for some reason I'm getting an error this time.

Have I missed a step? I'm not sure why this error is appearing.

Code

        public static readonly Func<CodySolutionEntities, IQueryable<Album>> SelectAlbums =
        CompiledQuery.Compile<CodySolutionEntities, IQueryable<Album>>(
            query => from q in query.Albums.Include("Photo")
                     select q);

Error

Error 1 The type 'CodyData.Diagram.CodySolutionEntities' cannot be used as type parameter 'TArg0' in the generic type or method 'System.Data.Objects.CompiledQuery.Compile<TArg0,TResult>(System.Linq.Expressions.Expression<System.Func<TArg0,TResult>>)'. There is no implicit reference conversion from 'CodyData.Diagram.CodySolutionEntities' to 'System.Data.Objects.ObjectContext'. C:\Users\Cody\Documents\CMBS\CodySolution\CodyData\Delegates\PhotoDelegates.cs 13 13 CodyData

Richard Schneider
  • 34,944
  • 9
  • 57
  • 73
Cody
  • 8,686
  • 18
  • 71
  • 126

1 Answers1

17

The error message indicates that CodySolutionEntities is not derived from ObjectContext, which is a problem because the CompiledQuery only works with an ObjectContext. In this case CodySolutionEntities must be derived from a DbContext object which, at this time, is the recommended context object to use.

The CompiledQuery probably worked in the past because, Entity Framework versions prior to 4.1 created an object derived from ObjectContext instead of DbContext for you to manage your entities.

Like this post explains, if you're able to target .NET 4.5 you can use EF 5, and you won't need the CompiledQuery anymore as it will automatically cache compiled LINQ to Entity queries for you. If not you may want to look into switching back to using an ObjectContext, but before doing that make sure your mindset isn't simply compiled or bust.

gowansg
  • 795
  • 1
  • 8
  • 15
  • What would be the equivalent way using `DbContext` to do what I'm trying to do, then? – Cody Jan 12 '13 at 06:53
  • 1
    That's the problem, you **cannot** use `DbContext` with `CompiledQuery`. See: http://stackoverflow.com/a/6731102/1289454 . Could you just stick with a query that isn't compiled? `using(var context = new CodySolutionEntities()){ var albums = context.Albums.Include(a => a.Photos); //... }` – gowansg Jan 12 '13 at 08:04
  • To answer your question, the equivalent is: public static readonly Func> SelectAlbums = query => from q in query.Albums.Include("Photo") select q; But I have no idea if this would be any more efficient than using it inline. – Tod Oct 18 '18 at 08:51