<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:a10="http://www.w3.org/2005/Atom" version="2.0">
  <channel xmlns:media="http://search.yahoo.com/mrss/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
    <title>ABP.IO Stories</title>
    <link>https://abp.io/community/articles</link>
    <description>A hub for ABP Framework, .NET, and software development. Access articles, tutorials, news, and contribute to the ABP community.</description>
    <lastBuildDate>Wed, 02 Dec 2026 11:43:55 Z</lastBuildDate>
    <generator>Community - ABP.IO</generator>
    <image>
      <url>https://abp.io/assets/favicon.ico/favicon-32x32.png</url>
      <title>ABP.IO Stories</title>
      <link>https://abp.io/community/articles</link>
    </image>
    <a10:link rel="self" type="application/rss+xml" title="self" href="https://abp.io/community/rss?member=hamzasallakh" />
    <item>
      <guid isPermaLink="true">https://abp.io/community/posts/polymorphic-associations-in-abp-when-flexibility-meets-data-integrity-gplryp4y</guid>
      <link>https://abp.io/community/posts/polymorphic-associations-in-abp-when-flexibility-meets-data-integrity-gplryp4y</link>
      <a10:author>
        <a10:name>hamzasallakh</a10:name>
        <a10:uri>https://abp.io/community/members/hamzasallakh</a10:uri>
      </a10:author>
      <category>entity-framework-core</category>
      <category>abp-framework</category>
      <category>modularity</category>
      <category>design-patterns</category>
      <category>software-architecture</category>
      <category>polymorphic-associations</category>
      <category>database-design</category>
      <category>data-integrity</category>
      <title>Polymorphic Associations in ABP: When Flexibility Meets Data Integrity</title>
      <description>Polymorphic Associations offer a flexible way to reference multiple entity types using EntityType and EntityId. But why are they considered a database antipattern, and why does ABP use them in CMS Kit? This article explores the trade-offs between data integrity, flexibility, and modularity, with practical examples and guidelines to help developers decide when the pattern is appropriate based on actual business requirements.</description>
      <pubDate>Wed, 02 Dec 2026 11:11:55 Z</pubDate>
      <a10:updated>2026-12-02T11:29:33Z</a10:updated>
      <content:encoded><![CDATA[<h1>Polymorphic Associations in ABP: When Flexibility Meets Data Integrity</h1>
<p>In software development, we often face a trade-off between building a flexible system and maintaining a reliable data model.</p>
<p>Imagine that you are building a comments feature. Initially, users can add comments to articles. Later, the business asks you to support comments on products, tickets, and other entities.</p>
<p>Should you create a separate relationship for every entity? Or should you build a generic comments module that can work with different entity types without knowing them in advance?</p>
<p>One possible solution is to use <strong>Polymorphic Associations</strong>.</p>
<p>This approach is used by several frameworks, including ABP. However, it is also described as a database antipattern by some experienced database professionals.</p>
<p>So why does ABP use it, and when should we consider using it in our own applications?</p>
<h2>Understanding Polymorphic Associations</h2>
<p>In a traditional relational database, a relationship is defined using a foreign key that references a specific table.</p>
<p>For example, a comment associated with an article might look like this:</p>
<pre><code class="language-csharp">public class Comment : AggregateRoot&lt;Guid&gt;
{
    public Guid ArticleId { get; private set; }

    public string Text { get; private set; }
}
</code></pre>
<p>This is simple, explicit, and allows the database to enforce referential integrity.</p>
<p>But what happens when the same comment entity needs to support products, tickets, and other resources?</p>
<p>Instead of creating a dedicated property for each entity type, we can represent the relationship using two properties:</p>
<pre><code class="language-csharp">public class Comment : AggregateRoot&lt;Guid&gt;
{
    public string EntityType { get; private set; }

    public Guid EntityId { get; private set; }

    public string Text { get; private set; }
}
</code></pre>
<p>The <code>EntityType</code> identifies the type of the referenced entity, while the <code>EntityId</code> identifies a specific instance of that type.</p>
<p>Our comments table might look like this:</p>
<p>| Id | EntityType | EntityId | Text |
|---|---|---|---|
| 1 | Article | A101 | Great article! |
| 2 | Product | P205 | Is this available? |
| 3 | Ticket | T310 | Please investigate. |</p>
<p><em>Identifiers are simplified for illustration.</em></p>
<p>This approach is known as a Polymorphic Association and was popularized by Ruby on Rails.</p>
<p>The main benefit is that we can support additional entity types without changing the comments table.</p>
<p>However, this flexibility comes at a cost.</p>
<h2>Why Is It Considered an Antipattern?</h2>
<p>The main concern with Polymorphic Associations is not the business requirement itself. It is how the relationship is represented in a relational database.</p>
<p>A traditional foreign key references a specific table. With <code>EntityType</code> and <code>EntityId</code>, the referenced table depends on the value stored in each record.</p>
<p>As a result, a conventional foreign key cannot enforce the relationship between the comment and its target entity.</p>
<p>This introduces several challenges:</p>
<ul>
<li>The referenced entity may not exist.</li>
<li>Deleting an entity may leave orphaned records.</li>
<li>Queries across different entity types may become more complex.</li>
<li>Maintaining referential integrity becomes an application-level responsibility unless another enforcement mechanism is introduced.</li>
</ul>
<p>GitLab discusses these problems in its <a href="https://docs.gitlab.com/development/database/polymorphic_associations/">database development guidelines</a> and recommends avoiding this approach.</p>
<p>Similarly, Bill Karwin dedicates an entire chapter to Polymorphic Associations in his book, <em>SQL Antipatterns, Volume 1: Avoiding the Pitfalls of Database Programming</em>.</p>
<p>However, under the section <em>Legitimate Uses of the Antipattern</em>, he also states:</p>
<blockquote>
<p>You may find that this antipattern is unavoidable if you use an object-relational programming framework such as Hibernate.</p>
</blockquote>
<p>He explains that a framework can reduce some of the risks by encapsulating the application logic responsible for maintaining referential integrity.</p>
<p>This is an important distinction. A pattern may introduce disadvantages at the database level while still providing architectural benefits in a particular context.</p>
<p>Using a framework does not automatically eliminate these disadvantages. We still need to understand and manage them.</p>
<h2>Why Does ABP Use Polymorphic Associations?</h2>
<p>A good example can be found in ABP's CMS Kit module.</p>
<p>CMS Kit provides reusable features such as comments, reactions, ratings, and marked items. These features can be integrated with different entities across different applications.</p>
<p>The <code>Comment</code> entity uses the following properties:</p>
<pre><code class="language-csharp">public virtual string EntityType { get; protected set; }

public virtual string EntityId { get; protected set; }
</code></pre>
<p>ABP also allows developers to register supported entity types through configuration:</p>
<pre><code class="language-csharp">Configure&lt;CmsKitCommentOptions&gt;(options =&gt;
{
    options.EntityTypes.Add(
        new CommentEntityTypeDefinition("Product")
    );
});
</code></pre>
<p>Now, an application can enable comments for its own product entity without modifying the CMS Kit module.</p>
<p>This is where the architectural context becomes important.</p>
<p>CMS Kit is designed to be a reusable module. It cannot know in advance which business entities will exist in every application that uses it.</p>
<p>Introducing a dependency on each of these entities would work against the purpose of building a reusable module.</p>
<p>Instead, ABP uses Polymorphic Associations to keep the module independent and extensible.</p>
<p>The same approach could be useful when building a generic chat module that allows conversations to be associated with orders, shipments, support tickets, or entities introduced by future modules.</p>
<p>In both cases, flexibility is not simply a technical preference. It serves an actual business and architectural requirement.</p>
<p>It is worth noting that ABP uses string identifiers in its CMS Kit implementation, allowing it to accommodate different identifier types. Applications using GUID identifiers exclusively may choose <code>Guid</code> instead.</p>
<h2>Let the Business Drive the Decision</h2>
<p>Consider two different scenarios.</p>
<p>In the first scenario, we are building an invoicing module. Every invoice line belongs to an invoice.</p>
<p>There is no meaningful reason to replace <code>InvoiceId</code> with <code>EntityType</code> and <code>EntityId</code>. The relationship is already clearly defined by the business, and a foreign key provides valuable guarantees.</p>
<p>In the second scenario, we are building a generic comments module that can be integrated with different business modules without knowing their entities in advance.</p>
<p>Here, the additional flexibility has a clear purpose.</p>
<p>Both scenarios involve relationships between entities, but they have different requirements.</p>
<p>The question should not be whether Polymorphic Associations are good or bad in general. Instead, we should ask whether the flexibility they introduce is worth the guarantees we give up.</p>
<h3>When does the pattern make sense?</h3>
<ul>
<li>When the business requires an extensible association across multiple entity types.</li>
<li>When building generic, reusable, or cross-module capabilities.</li>
<li>When introducing direct dependencies on business entities would compromise modularity.</li>
<li>When the required consistency and security can be maintained through other mechanisms.</li>
</ul>
<h3>When should we avoid it?</h3>
<ul>
<li>When the relationship is already known and clearly defined.</li>
<li>When conventional relationships satisfy the business requirements.</li>
<li>When database-enforced referential integrity is essential.</li>
<li>When flexibility is introduced only for possible future requirements.</li>
<li>When the primary goal is to avoid database migrations or reduce the number of tables.</li>
</ul>
<h2>Alternatives Worth Considering</h2>
<p>Polymorphic Associations are not the only way to associate an entity with multiple entity types.</p>
<p>In his article, <a href="https://hashrocket.com/blog/posts/modeling-polymorphic-associations-in-a-relational-database">Modeling Polymorphic Associations in a Relational Database</a>, Jack Christensen compares several approaches, including separate association tables and exclusive relationships using nullable foreign keys.</p>
<p>Another possible approach is to introduce a common parent entity that represents the different resource types.</p>
<p>These alternatives can provide stronger database-level guarantees, but they may introduce additional tables, constraints, or dependencies.</p>
<p>Microsoft Dataverse also supports polymorphic lookups, demonstrating that the need to reference multiple entity types exists in real-world platforms. However, platform-level support should not be confused with a particular physical database implementation.</p>
<p>The appropriate solution depends on the requirements and boundaries of the application.</p>
<h2>Using the Pattern Responsibly</h2>
<p>If we decide that Polymorphic Associations are appropriate, we should establish a few conventions:</p>
<ul>
<li>Use consistent property names: <code>EntityType</code> and <code>EntityId</code>.</li>
<li>Register supported entity types using stable identifiers.</li>
<li>Validate the existence of referenced entities where required.</li>
<li>Define what happens when a referenced entity is deleted or archived.</li>
<li>Add appropriate composite indexes.</li>
<li>Define consistency guarantees and test them.</li>
</ul>
<p>Authorization also deserves attention. A generic module should not assume that permission to use its features automatically grants access to every referenced entity.</p>
<p>The owning business module should remain responsible for its entity-specific access policies. This can be achieved through registered authorization providers without coupling the generic module to concrete business entities.</p>
<h2>Final Thoughts</h2>
<p>Polymorphic Associations are an interesting example of how database design and software architecture can have different priorities.</p>
<p>From a relational database perspective, the two-column approach introduces genuine concerns about referential integrity.</p>
<p>From a modular architecture perspective, it can provide valuable flexibility and reduce dependencies between modules, as demonstrated by ABP's CMS Kit.</p>
<p>Neither perspective is wrong.</p>
<p>The business determines whether flexibility is needed, while the architecture determines how that flexibility should be achieved and what trade-offs are acceptable.</p>
<p>My recommendation is simple:</p>
<p><strong>Prefer explicit relationships by default. Use Polymorphic Associations when a real business or architectural requirement justifies the trade-off.</strong></p>
<p>A pattern should be chosen because it solves a problem, not simply because it is available or because a framework uses it.</p>
<h2>References</h2>
<ol>
<li>Bill Karwin, <a href="https://pragprog.com/book/bksap1">SQL Antipatterns, Volume 1: Avoiding the Pitfalls of Database Programming</a>, Chapter 7: Polymorphic Associations, 2022.</li>
<li>Jack Christensen, <a href="https://hashrocket.com/blog/posts/modeling-polymorphic-associations-in-a-relational-database">Modeling Polymorphic Associations in a Relational Database</a>, Hashrocket.</li>
<li>GitLab, <a href="https://docs.gitlab.com/development/database/polymorphic_associations/">Polymorphic Associations — Database Development Guidelines</a>.</li>
<li>Microsoft, <a href="https://learn.microsoft.com/en-us/power-apps/developer/data-platform/entity-relationship-metadata">Table Relationship Definitions</a>.</li>
<li>Microsoft, <a href="https://learn.microsoft.com/en-us/power-apps/developer/data-platform/webapi/multitable-lookup">Multi-table Lookup Columns</a>.</li>
<li>ABP Framework, <a href="https://abp.io/docs/latest/modules/cms-kit/comments">CMS Kit: Comments</a>.</li>
<li>ABP Framework, <a href="https://github.com/abpframework/abp/tree/dev/modules/cms-kit">CMS Kit Source Code</a>.</li>
<li>ABP Framework, <a href="https://abp.io/docs/latest/framework/architecture/best-practices/entities">Entity Best Practices and Conventions</a>.</li>
</ol>
]]></content:encoded>
      <media:thumbnail url="https://abp.io/api/posts/cover-picture-source/3a2548a1-0f42-5698-a074-71f0d3c8905a" />
      <media:content url="https://abp.io/api/posts/cover-picture-source/3a2548a1-0f42-5698-a074-71f0d3c8905a" medium="image" />
    </item>
  </channel>
</rss>