ZZZ Code AI
Report Issues
Suggest Features
Login
EF Core Tools
Chat
Code Explain
More Tools
How to map entities in the 'OnModelCreating' method to implement a TPH inheritance in EF Core?
<p>To implement the TPH inheritance strategy in EF Core, you need to:</p> <ol> <li>Call the <code>HasDiscriminator<type>([DiscriminatorName])</code> method for your root entity</li> <li>Call the <code>HasValue([DiscriminatorName])</code> method for every concrete entity</li> </ol> <p>Here is an example:</p> <pre><code class="language-csharp">protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Animal>() .HasDiscriminator<string>("DiscriminatorColumnName") .HasValue<Cat>("Cat") .HasValue<Dog>("Dog"); } </code></pre> <p>In this configuration:</p> <ul> <li>The <code>Animal</code> is an abstract class, meaning you don't map it to a table.</li> <li>The <code>.HasDiscriminator<string>("DiscriminatorColumnName")</code> will create a column name named <code>DiscriminatorColumnName</code> of type <code>string</code>.</li> <li>The <code>HasValue<Cat>("Cat")</code> map the <code>Cat</code> type to the discriminator value <code>Cat</code>.</li> <li>The <code>HasValue<Dog>("Dog")</code> map the <code>Dog</code> type to the discriminator value <code>Dog</code>.</li> </ul>
Sponsored by
Entity Framework Extensions
This field is required
A text with a minimum of 10 characters is required
Send
Legal & Licensing
Answer generated by AI may produce inaccurate information about code, people, facts, and more.
Advertising Break!
5
seconds left
Did you know...
That you can now sponsor this project on
GitHub
?