Search code examples
entity-framework-coreforeign-keysnpgsql

Mark property as foreign key


I am using Microsoft.AspNetCore.Identity to manage users in my WebApp. I derived an ApplicationUser as follows:

public class ApplicationUser : IdentityUser 
{
    public string TgUserName { get; set; }
}

Now I have another entity let's call it Player which is managed by an ApplicationUser.

public string Id { get; set; }

public string ApplicationUserId { get; set; }

I purposely do not want to create a property of type ApplicationUser and have to mess around with include statements when retrieving objects from the database. I do want to have a property that holds the primary key which I then use to retrieve those objects on demand.

How can I tell EF Core that ApplicationUserId is a foreign key to ApplicationUser.Id.


Solution

  • You can do that by using the fluent API. First you need to define the relationship using the appropriate Has / With call overloads, and then use the HasForeignKey to map the property as FK.

    In this particular case (many-to-one, no navigation properties on both ends, explicit FK property) it should be something like this:

    modelBuilder.Entity<Player>()
        .HasOne<ApplicationUser>() // no reference navigation property
        .WithMany() // no collection navigation property
        .HasForeignKey(e => e.ApplicationUserId) // FK property
        .IsRequired(); // remove this if the relationship is optional
    

    For more info, see Relationships - Manual configuration, Foreign key, Required and optional relationships sections of the official EF Core documentation.