-
Notifications
You must be signed in to change notification settings - Fork 12
Entity Framework
ModelMetadata can be generated automatically from an EDMX file or a Code-First DbContext, using the LazyEntityGraph.EntityFramework library.
For each method, the MetadataWorkspace
is retrieved using Entity Framework, and then processed to extract entity types and relationships. The MetadataWorkspace
is cached as a private static member per context.
To generate metadata from an EDMX, call ModelMetadataGenerator.LoadFromEdmxContext<TContext>(string contextName)
(source).
The contextName
argument is the name of your EDMX model. You can find this in the metadata
part of your connection string; for example, if your connection string contains metadata=res://*/MyContextName.csdl|res://*/MyContextName.ssdl|res://*/MyContextName.msl
then the context name is MyContextName.
To generate metadata from a Code-First DbContext, call ModelMetadataGenerator.LoadFromCodeFirstContext<TContext>(Func<string, TContext> createFromConnectionString, bool hardCache)
(source).
The function to be passed to this method must pass the input string to the DbContext's constructor, which should then call base(string nameOrConnectionString)
. This is so that the DbContext can be instantiated without initializing a connection to the database. This method then uses Entity Framework's EdmxWriter
to write the DbContext out to an in-memory XML stream, then processes the XML manually to generate the MetadataWorkspace
.
The call to EdmxWriter.WriteEdmx
can take a long time. For this reason, the method provides a boolean flag, hardCache
, which will write the generated EDMX file to disk when set to true
. It uses the most recent DbMigration
as a file name, so every time the model is updated the EDMX file is regenerated.