Entity Framework - Where is my Object Context?
Asked Answered
D

3

17

Ok, I'm obviously missing something very basic. I'm very new to Entity Framework.

I want to call stored procedures without importing them, so I was planning on using ExecuteStoreQuery(). According to the documentation, ExecuteStoreQuery is a method of ObjectContext. But, I have no idea where to get my ObjectContext.

I generated my entites using Database First. So far, I have been accessing my entities something like this:

var db = new MyEntities();

PRODUCT p = db.PRODUCTS.First(a => a.PRODUCTSKEY == thekey);

But I can't call db.ExecuteStoreQuery, becase db isn't an ObjectContext.

I've googled how to get ObjectContext from an entity. I find some answers, but they're all flagged with cautions, saying that it's a workaround, and only to use it if you have no other option. Ok, so what is the RIGHT way?

All examples that I've found for using ExecuteStoreQuery assume that you already have your ObjectContext. Not very helpful.

I found one website that stated that the ObjectContext is "automatically generated" by Entity Framework. If that's the case, then where is it?

I'm obviously missing something very simple here. This can't be that difficult.

Duwe answered 9/1, 2013 at 19:43 Comment(2)
db.ExecuteStoreQuery()?Carleecarleen
@Carleecarleen No. db is a DbContext instance which has no such method: msdn.microsoft.com/en-us/library/…Malissa
S
36

To get to the ObjectContext of your DbContext, all you'd need to do is the following:

var objectContext = ((IObjectContextAdapter)myDbContextObject).ObjectContext;
Shultz answered 9/1, 2013 at 19:49 Comment(0)
M
14

ObjectContext was replaced by DbContext in Entity Framework 4.1. Actually DbContext is an adapter (wrapper) over ObjectContext. If you need to get ObjectContext you can cast your DbContext instance to IObjectContextAdapter interface (it is implemented explicitly) and wrapped ObjectContext instance will be available:

ObjectContext context = ((IObjectContextAdapter)db).ObjectContext;

BTW I think you are looking for db.Database.SqlQuery method.

Mainstay answered 9/1, 2013 at 20:0 Comment(1)
Actually the replacement happened in EF 4.1, with the introduction of Code-First, see this link: blogs.msdn.com/b/adonet/archive/2011/01/27/…Shultz
L
1

In Your case MyEntities is your ObjectContext.

Technically it is auto-generated class by EntityFramework that inherits from ObjectContext class.

Loft answered 9/1, 2013 at 19:46 Comment(2)
Ok, if I try: MyEntities.ExecuteStoreQuery(MyQuery), the compiler says that MyEntities "does not contain a definition for 'ExecuteStoreQuery'"Duwe
Others are correct, depends which version of EF you are using, for EF4 and earlier, you should be able to follow steps here: blogs.microsoft.co.il/blogs/gilf/archive/2009/03/06/…Loft

© 2022 - 2024 — McMap. All rights reserved.