dotnet / dotnet/efcore

[ForeignKey] ignored with alternate principal key

Open
#29,448 2 comments 0 reactions 1 assignee Claimed by @AndriySvyryd View on GitHub
area-model-building
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

This code...

```cs
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().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.

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.