dotnet / dotnet/aspnetcore

Identity: Check/ensure that base.OnModelCreating is called when AppDbContext inherits from IdentityDbContext.

Open
#52,314 0 comments 0 reactions 0 assignees View on GitHub
analyzer area-identity enhancement Pillar: Dev Experience
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Is your feature request related to a problem? Please describe the problem.

It's very easy to forget adding `base.OnModelCreating(modelBuilder);` call when switching inheritance from `DbContext` to `IdentityDbContext`

And as a result, one will get the following exception from EF Core:

> System.InvalidOperationException : The entity type 'IdentityUserLogin' requires a primary key to be defined.

IMO, this is a very unfriendly message, because it's not telling how to fix the problem in the first place. Unless you google and find the answer on [Stack Overflow](https://stackoverflow.com/questions/40703615/the-entity-type-identityuserloginstring-requires-a-primary-key-to-be-defined). I believe framework should guide with errors, not frighten.

### Describe the solution you'd like

An easy solution is to provide an analyzer that will check for the base call, or even an interceptor to fix the issue silently.

The ideal solution for me would be, if C#/CLR allowed implementing Template Method pattern with reusing the name:

```
class IdentityContext
{
protected override sealed void OnModelCreating(ModelBuilder modelBuilder)
{
...
new.OnModelCreating(modelBuilder);
}

new protected virtual void OnModelCreating(ModelBuilder modelBuilder)
{
}
}
```

### Additional context

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.