1

Is there a way to materialize an instance of your own class that derives from the entity type specified in your model? Let's say I have a "ClassName" property in my model for a given entity and whenever EF materializes an instance of the entity, I want to create an instance of the specified ClassName instead (which is a sub-class of the entity of course).

I know there is the ObjectMaterialized event on the ObjectContext but at this point the entity is already created.

var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
objectContext.ObjectMaterialized += OnObjectMaterialized;

I need a hook right before this to customize the object creation. You might ask why on earth would I need to do this. I have a large object model that changes constantly so I can't define all my classes in the EDMX. The properties that I store in the database can be abstracted to a couple classes at the top of the object model hierarchy. I intend to create entities for those using table-per-type inheritance. But if I could retrieve specific object instances directly when using EF that would be awesome.

Thanks!

3
  • 1
    Not an answer to your question, but the generated entity classes are partial. Can you not simply add your needed functionality to those partial classes? Commented Nov 14, 2013 at 10:14
  • To add to @oerkelens' comment, you could also use an extension class. Messing with the generation might come back and bite you when there's a change in class generation Commented Nov 14, 2013 at 13:17
  • Adding methods or properties through the partial class won't be enough. I need to create a whole object model with inheritance under the entity classes. Commented Nov 14, 2013 at 21:31

1 Answer 1

1

I wanted to create custom proxys and debugged deep into the entity framework. I found the translator class, which is responsible to create the entities by reflection. The namespace of the class is System.Data.Entity.Core.Common.Internal.Materialization.

The method creating the entites is the private method Emit_ConstructEntity. The entity type is a parameter and is created by the private method LookupObjectMapping based on an EdmType object (I was using model first).

If you want to change the class, which are created, you have to create a custom MetaDataWorkspace. The workspace is responsible to select the EdmType. Maybe try to debug into the methods yourself and have a look how the MetaDataWorkspace is used to identify the CLR type.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.