Search code examples
c#linqentity-frameworkobjectcontext

ObjectMaterialize in EF not firing on first level query


I have a query such as:

Query Syntax 1 - Does not fire the somehandler;
var results = (from I in db.mytable
              select new myObject() {
                        column1 = i.Prop1
              }).ToList();

Query Syntax 2 - Does fires the somehandler event;
var results = (from I in db.mytable
               select I).toList();

in my ContextClass I have something like this:

((IOjectContextAdapter)this).ObjectContext.ObjectMaterialized +=  somehandler;

The only difference I see is that the first query builds a new object from the select results.

Any idea why the event wouldn't fire?


Solution

  • The event fires only for Entity object projections, that is why you see this behaviour.

    "If the query used a projection and there is no matching entity, the results are materialized into DbDataRecords (or anonymous types when a LINQ to Entities query was used) instead of entity objects," Ref -Programming Entity Framework (Julia Lerman)P-244)

    The definition for ObjectMarialized states

    Occurs when a new entity object is created from data in the data source as part of a query or load operation.

    Ref. https://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.objectmaterialized(v=vs.110).aspx

    Since the projection does not create an Entity object, it does not fire the event.