Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ExecuteStoreQuery with Dbcontext

Tags:

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?

like image 457
Chuck Norris Avatar asked Dec 28 '11 13:12

Chuck Norris


People also ask

Should you use using with DbContext?

EF and EF Core DbContext types implement IDisposable . As such, best practice programming suggests that you should wrap them in a using() block (or new C# 8 using statement). Unfortunately, doing this, at least in web apps, is generally a bad idea.

Can we use SQL query in Entity Framework?

Entity Framework allows you to execute raw SQL queries for the underlying relational database.

Can Entity Framework call Stored Procedure?

The Entity Framework has the capability of importing a Stored Procedure as a function. We can also map the result of the function back to any entity type or complex type.


2 Answers

A DbContext is simply a wrapper around the ObjectContext.

You can still access the original ObjectContext by using IObjectContextAdapter

(dbContext as IObjectContextAdapter).ObjectContext; 
like image 115
Wouter de Kort Avatar answered Oct 04 '22 00:10

Wouter de Kort


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

dbContext.Database.SqlQuery<T>(string sql); 
like image 25
Tesserex Avatar answered Oct 04 '22 00:10

Tesserex