Skip to content

[ForeignKey] ignored with alternate principal key #29448

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
bricelam opened this issue Oct 27, 2022 · 2 comments
Open

[ForeignKey] ignored with alternate principal key #29448

bricelam opened this issue Oct 27, 2022 · 2 comments

Comments

@bricelam
Copy link
Contributor

This code...

class TestContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlServer(@"Data Source=(local)\MSSQLLocalDB;Initial Catalog=TestApp");

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Car>().HasOne(d => d.Color).WithMany()
            .HasPrincipalKey(p => p.ColorCode);
    }
}

class Car
{
    public int Id { get; set; }

    public string? ColorCode { get; set; }

    [ForeignKey(nameof(ColorCode))]
    public virtual Color? Color { get; set; }
}

class Color
{
    public int Id { get; set; }

    public string ColorCode { get; set; } = null!;
}

...produces this model.

EntityType: Car
  Properties:
    Id (int) Required PK AfterSave:Throw ValueGenerated.OnAdd
    ColorCode (string)
    ColorCode1 (no field, string) Shadow FK Index
  Navigations:
    Color (Color) ToPrincipal Color
  Keys:
    Id PK
  Foreign keys:
    Car {'ColorCode1'} -> Color {'ColorCode'} ToPrincipal: Color ClientSetNull
  Indexes:
    ColorCode1

The ForeignKey attribute is completely ignored. A ColorCode1 shadow property is introduced instead.

@ajcvickers
Copy link
Contributor

Note from triage: Likely fix is to re-trigger the foreign key attribute convention when the principal key changes.

@AndriySvyryd
Copy link
Member

Could be related to #30344

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants