I would like to define foreign key in C# DB Context (method OnModelCreating
) using only identifier column.
All examples I saw relies on assumption you have C# reference within types, like:
public sealed class Answer
{
public long UserId { get; set; }
public User User { get; set; } = null!;
...
so then you write:
modelBuilder.Entity<Answer>(entity =>
{
...
entity.HasOne(d => d.User).WithMany(p => p.Answers)
.HasForeignKey(d => d.UserId)
.OnDelete(DeleteBehavior.ClientSetNull);
But how to define (in C#) foreign key when the type does not have reference and only identifier, like this:
public sealed class Answer
{
public long UserId { get; set; }
...
Solution -- "add reference and then follow the examples" does not count :-).