24

I want to use ExecuteStoreQuery function of Entity Framework and I was wondered that my context variable didn't have ExecuteStoreQuery method.

So, I discovered that it's a method of ObjectContext class, but I've already used DbContext for my application. I simply had tried to change DbContext with ObjectContext, but it brought some errors(for example, in ObjectContext isn't OnModelCreating method).

How can I use ExecuteStoreQuery with DbContext and if I can't, is any alternatives of ExecuteStoreQuery in DbContext?

Chuck Norris
  • 15,207
  • 15
  • 92
  • 123

2 Answers2

38

I want to add that I think now the correct method is:

dbContext.Database.SqlQuery<T>(string sql);
Tesserex
  • 17,166
  • 5
  • 66
  • 106
  • 2
    If you want to track changes to the returned objects, you should consider dbContext.tablename.SqlQuery(...) where tablename is your collection name. (i.e. a DbSet) – Carlos P Mar 31 '13 at 16:15
38

A DbContext is simply a wrapper around the ObjectContext.

You can still access the original ObjectContext by using IObjectContextAdapter

(dbContext as IObjectContextAdapter).ObjectContext;
Wouter de Kort
  • 39,090
  • 12
  • 84
  • 103