I get the exception ‘The entity type [TYPE] is not part of the model for the current context.’ when trying to run my application.
My best guess so far is that it doesn’t recognize my type as a type that it has mapped. This could very well be since it is a type loaded at runtime. This type comes from a different assembly.
How does EF: CF find all it’s entities to map, and how can I make it find my types ?
EF is not designed to support this feature directly. EF is ORM and ORM is mostly created for purpose when you specify types you want to use and map at design time and simply use them at runtime. It doesn’t mean that it is not possible to create types at runtime (with code mapping) but it is much more complex.
Context must know about all types it should map and about their mapping. If you create context with no reference to your new type it simply doesn’t know about it. How to solve it? I can think about two options:
DbSet<YourEmittedEntityType>(to use default mapping conventions) or emitOnModelCreatingmethod as well to specify custom mapping.EntityTypeConfiguration<YourEmittedEntityType>) class for your new entity as well. This class will specify mapping of new entity to your database table. Once you have your configuration you can manually createDbModelBuilderregister all necessary entity type configuration including your new ones created at runtime, buildDbModel, compile it and useDbCompiledModelto construct new instance of theDbContext. Just make user you cacheDbCompiledModelfor subsequent usages because its construction is very time consuming.In both cases make sure that table used to persist and retrieve new entity is already created and turn off any database initializers – you must maintain your database manually.
Sure this is only the first step. Now you need to emit / generate code which will use your new entity and context – be aware that EF doesn’t work with interfaces and inheritance is handled specially so in the most scenarios you need code working with your emitted type directly.