Polymorphic Associations in ABP: When Flexibility Meets Data Integrity

cover

In software development, we often face a trade-off between building a flexible system and maintaining a reliable data model.

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.

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?

One possible solution is to use Polymorphic Associations.

This approach is used by several frameworks, including ABP. However, it is also described as a database antipattern by some experienced database professionals.

So why does ABP use it, and when should we consider using it in our own applications?

Understanding Polymorphic Associations

In a traditional relational database, a relationship is defined using a foreign key that references a specific table.

For example, a comment associated with an article might look like this:

public class Comment : AggregateRoot<Guid>
{
    public Guid ArticleId { get; private set; }

    public string Text { get; private set; }
}

This is simple, explicit, and allows the database to enforce referential integrity.

But what happens when the same comment entity needs to support products, tickets, and other resources?

Instead of creating a dedicated property for each entity type, we can represent the relationship using two properties:

public class Comment : AggregateRoot<Guid>
{
    public string EntityType { get; private set; }

    public Guid EntityId { get; private set; }

    public string Text { get; private set; }
}

The EntityType identifies the type of the referenced entity, while the EntityId identifies a specific instance of that type.

Our comments table might look like this:

Id EntityType EntityId Text
1 Article A101 Great article!
2 Product P205 Is this available?
3 Ticket T310 Please investigate.

Identifiers are simplified for illustration.

This approach is known as a Polymorphic Association and was popularized by Ruby on Rails.

The main benefit is that we can support additional entity types without changing the comments table.

However, this flexibility comes at a cost.

Why Is It Considered an Antipattern?

The main concern with Polymorphic Associations is not the business requirement itself. It is how the relationship is represented in a relational database.

A traditional foreign key references a specific table. With EntityType and EntityId, the referenced table depends on the value stored in each record.

As a result, a conventional foreign key cannot enforce the relationship between the comment and its target entity.

This introduces several challenges:

  • The referenced entity may not exist.
  • Deleting an entity may leave orphaned records.
  • Queries across different entity types may become more complex.
  • Maintaining referential integrity becomes an application-level responsibility unless another enforcement mechanism is introduced.

GitLab discusses these problems in its database development guidelines and recommends avoiding this approach.

Similarly, Bill Karwin dedicates an entire chapter to Polymorphic Associations in his book, SQL Antipatterns, Volume 1: Avoiding the Pitfalls of Database Programming.

However, under the section Legitimate Uses of the Antipattern, he also states:

You may find that this antipattern is unavoidable if you use an object-relational programming framework such as Hibernate.

He explains that a framework can reduce some of the risks by encapsulating the application logic responsible for maintaining referential integrity.

This is an important distinction. A pattern may introduce disadvantages at the database level while still providing architectural benefits in a particular context.

Using a framework does not automatically eliminate these disadvantages. We still need to understand and manage them.

Why Does ABP Use Polymorphic Associations?

A good example can be found in ABP's CMS Kit module.

CMS Kit provides reusable features such as comments, reactions, ratings, and marked items. These features can be integrated with different entities across different applications.

The Comment entity uses the following properties:

public virtual string EntityType { get; protected set; }

public virtual string EntityId { get; protected set; }

ABP also allows developers to register supported entity types through configuration:

Configure<CmsKitCommentOptions>(options =>
{
    options.EntityTypes.Add(
        new CommentEntityTypeDefinition("Product")
    );
});

Now, an application can enable comments for its own product entity without modifying the CMS Kit module.

This is where the architectural context becomes important.

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.

Introducing a dependency on each of these entities would work against the purpose of building a reusable module.

Instead, ABP uses Polymorphic Associations to keep the module independent and extensible.

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.

In both cases, flexibility is not simply a technical preference. It serves an actual business and architectural requirement.

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 Guid instead.

Let the Business Drive the Decision

Consider two different scenarios.

In the first scenario, we are building an invoicing module. Every invoice line belongs to an invoice.

There is no meaningful reason to replace InvoiceId with EntityType and EntityId. The relationship is already clearly defined by the business, and a foreign key provides valuable guarantees.

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.

Here, the additional flexibility has a clear purpose.

Both scenarios involve relationships between entities, but they have different requirements.

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.

When does the pattern make sense?

  • When the business requires an extensible association across multiple entity types.
  • When building generic, reusable, or cross-module capabilities.
  • When introducing direct dependencies on business entities would compromise modularity.
  • When the required consistency and security can be maintained through other mechanisms.

When should we avoid it?

  • When the relationship is already known and clearly defined.
  • When conventional relationships satisfy the business requirements.
  • When database-enforced referential integrity is essential.
  • When flexibility is introduced only for possible future requirements.
  • When the primary goal is to avoid database migrations or reduce the number of tables.

Alternatives Worth Considering

Polymorphic Associations are not the only way to associate an entity with multiple entity types.

In his article, Modeling Polymorphic Associations in a Relational Database, Jack Christensen compares several approaches, including separate association tables and exclusive relationships using nullable foreign keys.

Another possible approach is to introduce a common parent entity that represents the different resource types.

These alternatives can provide stronger database-level guarantees, but they may introduce additional tables, constraints, or dependencies.

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.

The appropriate solution depends on the requirements and boundaries of the application.

Using the Pattern Responsibly

If we decide that Polymorphic Associations are appropriate, we should establish a few conventions:

  • Use consistent property names: EntityType and EntityId.
  • Register supported entity types using stable identifiers.
  • Validate the existence of referenced entities where required.
  • Define what happens when a referenced entity is deleted or archived.
  • Add appropriate composite indexes.
  • Define consistency guarantees and test them.

Authorization also deserves attention. A generic module should not assume that permission to use its features automatically grants access to every referenced entity.

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.

Final Thoughts

Polymorphic Associations are an interesting example of how database design and software architecture can have different priorities.

From a relational database perspective, the two-column approach introduces genuine concerns about referential integrity.

From a modular architecture perspective, it can provide valuable flexibility and reduce dependencies between modules, as demonstrated by ABP's CMS Kit.

Neither perspective is wrong.

The business determines whether flexibility is needed, while the architecture determines how that flexibility should be achieved and what trade-offs are acceptable.

My recommendation is simple:

Prefer explicit relationships by default. Use Polymorphic Associations when a real business or architectural requirement justifies the trade-off.

A pattern should be chosen because it solves a problem, not simply because it is available or because a framework uses it.

References

  1. Bill Karwin, SQL Antipatterns, Volume 1: Avoiding the Pitfalls of Database Programming, Chapter 7: Polymorphic Associations, 2022.
  2. Jack Christensen, Modeling Polymorphic Associations in a Relational Database, Hashrocket.
  3. GitLab, Polymorphic Associations — Database Development Guidelines.
  4. Microsoft, Table Relationship Definitions.
  5. Microsoft, Multi-table Lookup Columns.
  6. ABP Framework, CMS Kit: Comments.
  7. ABP Framework, CMS Kit Source Code.
  8. ABP Framework, Entity Best Practices and Conventions.