Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework: ObjectContext.ExecuteStoreQuery produces detached objects

I need to run some custom SQL to return a list of objects from a table. I'm using ExecuteStoreQuery for that.

var q = context.ExecuteStoreQuery<ProductionUnit>(MySelectString, new SqlParameter("@ProductionUnitId", value));

This does result in q containing an ObjectResult collection, but the actual ProductionUnit elements are Detached and their EntityKey is null. This creates a number of issues when trying to work on some of these objects or their relationships. My SQL query returns a result set containing all the columns of the respective ProductionUnits table (and nothing more).

Anything else I need to do in order to have these objects tracked or is this behavior by design?

like image 385
neaorin Avatar asked Feb 04 '10 16:02

neaorin


People also ask

What is ObjectContext in Entity Framework?

The ObjectContext class is the primary class for interacting with data as objects that are instances of entity types that are defined in a conceptual model. An instance of the ObjectContext class encapsulates the following: A connection to the database, in the form of an EntityConnection object.

What is detach in C#?

Removes the object from the object context. public: void Detach(System::Object ^ entity); C# Copy.


2 Answers

Solved it myself - you need to use the ExecuteStoreQuery overload which allows you to specify the EntitySet name for your returned entities.

like image 151
neaorin Avatar answered Oct 30 '22 18:10

neaorin


As there doesn't seem to be an accepted answer with code...

As @neaorin says, to ensure changes to returned entities are tracked, use the method

ExecuteStoreQuery<..>(commandText, entitySetName, MergeOptions, args paramaters)

as follows:

string strQuery = "SELECT * FROM employees WHERE id=999";
List<employee> employees;
services = context.ExecuteStoreQuery<employee>(strQuery, "employees", System.Data.Objects.MergeOption.AppendOnly).ToList();

The MergeOptions parameter dictates what the Framework does if some of these returned entities are already floating around in the context, i.e. whether to overwrite them or use the existing objects (the default).

like image 2
Carlos P Avatar answered Oct 30 '22 16:10

Carlos P