Skip to content

Allow FKs to have a different type from PKs in the snapshot #30827

Closed

Description

@renagaev

I have database schema where FK column type differs from PK column type it points to. Every new migration contains stange changes even when there is no model changes.

Steps to reproduce:

Create project with this code:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Npgsql;

namespace EfIssue;

public class Bank
{
    public long Id { get; set; }
    public ICollection<Account> Accounts { get; set; }
}

public class Account
{
    public long Id { get; set; }
    public Bank Bank { get; set; }
    public long BankId { get; set; }
}

public class AppDbContext : DbContext
{
    public DbSet<Bank> Banks { get; set; }
    public DbSet<Account> Accounts { get; set; }

    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Bank>();
        builder.Entity<Account>()
            .HasOne(x => x.Bank)
            .WithMany(x => x.Accounts)
            .HasForeignKey(x => x.BankId);

        builder.Entity<Account>().Property(x => x.BankId).HasColumnType("smallint");
    }
}

internal class DbDesignFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    public AppDbContext CreateDbContext(string[] args)
    {
        var dataSourceBuilder = new NpgsqlDataSourceBuilder(
            "Host=localhost;Database=eftest;Username=postgres;Password=postgres;");
        var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
        optionsBuilder.UseNpgsql(dataSourceBuilder.Build());
        return new AppDbContext(optionsBuilder.Options);
    }
}

Used packages:

<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.5">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.4" />

Run dotnet ef migrations add

Every new migration after initial will contains these changes:

migrationBuilder.DropForeignKey(
    name: "FK_Accounts_Banks_BankId",
    table: "Accounts");

migrationBuilder.DropUniqueConstraint(
    name: "AK_Banks_TempId",
    table: "Banks");

migrationBuilder.DropColumn(
    name: "TempId",
    table: "Banks");

migrationBuilder.AddForeignKey(
    name: "FK_Accounts_Banks_BankId",
    table: "Accounts",
    column: "BankId",
    principalTable: "Banks",
    principalColumn: "Id",
    onDelete: ReferentialAction.Cascade);

Possibly related: #27619 #27549
Is there any workaround?

Activity

  1. ajcvickers commented on May 5, 2023

    @ajcvickers
    Contributor

    Note for triage: still repros on latest daily, and on SQL Server.

  2. self-assigned this
    on May 10, 2023
  3. added this to the 8.0.0 milestone on May 10, 2023
  4. self-assigned this
    on Sep 5, 2023
  5. bricelam commented on Sep 5, 2023

    @bricelam
    Contributor

    The model snapshot looks correct. I suspect this is an issue/difference in model building with shadow/indexer properties.

    modelBuilder.Entity("Account", b =>
    {
        b.Property<short>("BankId")
            .HasColumnType("smallint");
    });
    
    modelBuilder.Entity("Bank", b =>
    {
        b.Property<long>("Id")
            .HasColumnType("bigint");
    });
    
    modelBuilder.Entity("Account", b =>
    {
        b.HasOne("Bank", "Bank")
            .WithMany("Accounts")
            .HasForeignKey("BankId");
    });
      Model: 
        EntityType: Account
          Properties: 
            Id (long) Required PK AfterSave:Throw ValueGenerated.OnAdd
    -       BankId (long) Required FK Index
    +       BankId (short) Required FK Index
          Navigations: 
            Bank (Bank) ToPrincipal Bank Inverse: Accounts
          Keys: 
            Id PK
          Foreign keys: 
    -       Account {'BankId'} -> Bank {'Id'} Required Cascade ToDependent: Accounts ToPrincipal: Bank
    +       Account {'BankId'} -> Bank {'TempId'} Required Cascade ToDependent: Accounts ToPrincipal: Bank
          Indexes: 
            BankId
        EntityType: Bank
          Properties: 
            Id (long) Required PK AfterSave:Throw ValueGenerated.OnAdd
    +       TempId (short) Required AlternateKey AfterSave:Throw
          Navigations: 
            Accounts (ICollection<Account>) Collection ToDependent Account Inverse: Bank
          Keys: 
            Id PK
  6. removed their assignment
    on Sep 5, 2023
  7. bricelam commented on Sep 5, 2023

    @bricelam
    Contributor

    Oh wait, Property<short>("BankId") looks wrong. That should be long not short.

    Changing it in the snapshot fixes the incorrect operations.

  8. self-assigned this
    on Sep 5, 2023
  9. bricelam commented on Sep 5, 2023

    @bricelam
    Contributor

    Hmm, this is happening because the model has a value converter (between int and short) on the property, and we erase type converters in the model snapshot. This is to avoid referencing app-specific types (like enums) that might evolve over the lifetime of the application.

    What are your thoughts on fixing this, @AndriySvyryd and @ajcvickers? Can we somehow detect that it's a simple cast conversion between two provider types and thus safe to keep the value conversion in the snapshot?

  10. AndriySvyryd commented on Sep 5, 2023

    @AndriySvyryd
    Member

    The snapshot should always store the provider type to avoid dealing with value converters.

  11. bricelam commented on Sep 7, 2023

    @bricelam
    Contributor

    Ok, then this is a model building error. The snapshot model should use the existing Id column (even though it has a different CLR type) rather than introducing TempId.

  12. removed their assignment
    on Sep 7, 2023
  13. 6 remaining items

  14. changed the title [-]Using FK with HasColumnType causes strange migration changes[/-] [+]Allow FKs to have a different type from PKs in the snapshot[/+] on Oct 23, 2024
  15. added theissue type on Jun 15, 2025
  16. added
    priority-bug
    on Dec 3, 2025
  17. modified the milestones: Backlog, 11.0.0 on Jun 19, 2026
  18. added a commit that references this issue on Jun 19, 2026
    7fe7560
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

area-migrationsarea-model-buildingcustomer-reportedpreview-6priority-bug

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions