Search code examples
entity-framework-coreef-code-first

How can I access Entity Type information in EF Core with code first?


In Entity Framework Core, how can I access the Entity Type data (the entity names, regular properties, navigation properties, etc.) when using code-first? When using database-first, I can use Scaffolding or Reverse Engineering and from EF Core 7 onward, I can even use Custom Reverse Engineering Templates. I'd like to be able to access the same Entity Type information when using code-first whether that be in T4 or in plain C#. Based on the default T4 template in EF Core 7, the information I am after is in the Model parameter (of type Microsoft.EntityFrameworkCore.Metadata.IModel) that gets set as a parameter:

<#@ parameter name="Model" type="Microsoft.EntityFrameworkCore.Metadata.IModel" #>

I'm essentially asking a variation of this EF 6 question about DbContext Generation T4 Templates With Code-First but for EF Core.


Solution

  • You can access it on an instance of DbContext. There is property Model available.

    Related information

    DbContext.Model Property