0

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 :-).

greenoldman
  • 16,895
  • 26
  • 119
  • 185
  • 1
    What's your use case? I guess it's a API for a single table and therefore, no `User` entities – Cid Jun 28 '23 at 16:05
  • Why do it need this reference? The entity (class) `User` exists? – vernou Jun 28 '23 at 16:15
  • @Cid, the other table exists. I simply don't want to add a reference between types, only identifiers. – greenoldman Jun 28 '23 at 16:21
  • @vernou Well, I don't see method `HasForeignKey` directly defined on `entity` object (when defining `Entity` in model builder). The class `User` exists (and table as well). – greenoldman Jun 28 '23 at 16:22
  • 2
    @greenoldman did you check [this](https://stackoverflow.com/questions/20886049/ef-code-first-foreign-key-without-navigation-property) ? – Cid Jun 28 '23 at 16:27
  • 1
    @Cid, great, thank you, this solved my problem. – greenoldman Jun 28 '23 at 16:40

0 Answers0