3

I use entity framework and Im trying to make such a query generic, so it can be used for any entity type (with an assumption that each entity has property int Id).

I tried something like this, but there is no collection ctx.TEntity or something similiar:

public class Queries<TEntity> where TEntity : AbstractEntity
{
  public Func<AdventureWorksEntities, int, TEntity> getQuery() {
   return
    CompiledQuery.Compile<AdventureWorksEntities, int, Entity>(
    (ctx, num) => ctx.TEntity.First(x => x.Id>num));
    }
}

AbstractEnitity:

public abstract class AbstractEntity {

[Key]
public int Id {get; set};
}

Thanks for your ideas :)

John Smith
  • 1,783
  • 6
  • 22
  • 36
  • What is the version of Entity Framework ? Do you use ObjectContext or DbSet ? – Rom Eh Oct 23 '13 at 07:57
  • I use EF6 Code First - and I have access both to ObjectContext and DbContext. DbSet I defined as properties in my DbContext class. – John Smith Oct 23 '13 at 08:17
  • 1
    I tried Compiled Queries with a DbContext, with no success (it is not supported, and the workaround were not suitable for me too). Have you checed this link : http://blogs.msdn.com/b/efdesign/archive/2011/06/30/auto-compiled-linq-queries-entity-framework-june-2011-ctp.aspx ? – Rom Eh Oct 23 '13 at 09:05
  • oh, so I guess now there is no need to create compiledQuery manually, but what if want even the first rn of the query to be faster? is there any way how to create compiledQuery manually even in EF6? – John Smith Oct 23 '13 at 09:56
  • You can see this article : http://social.msdn.microsoft.com/Forums/en-US/0c07e1d6-7db6-4348-b106-e576d3153b70/ef-40-compiled-queries-performance?forum=adonetefx. I don't think using Compiled Queires make a big difference espacially with modern versions of EF (5 & 6). – Rom Eh Oct 23 '13 at 14:47
  • Ok, thank you :) in my case I wait a long time for the first query to be executed, but maybe it is just because it is the first query asked to the database ever since the program had started – John Smith Oct 25 '13 at 07:23

1 Answers1

4

I tried Compiled Queries with a DbContext, with no success (it is not supported, and the workaround were not suitable for me too). Have you checed this link : http://blogs.msdn.com/b/efdesign/archive/2011/06/30/auto-compiled-linq-queries-entity-framework-june-2011-ctp.aspx ?

You can see this article : http://social.msdn.microsoft.com/Forums/en-US/0c07e1d6-7db6-4348-b106-e576d3153b70/ef-40-compiled-queries-performance?forum=adonetefx. I don't think using Compiled Queires make a big difference espacially with modern versions of EF (5 & 6).

On the first query, the connection is set up, and it can take some time.

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
Rom Eh
  • 1,981
  • 1
  • 16
  • 33