EF Core composite key with relation

  Kiến thức lập trình

I have the following classes representing that one Account can have multiple Profiles (simplified for easier understanding):

public record ProfileId(string Value);
public record AccountId(string Value);
public record UserId(string Value);

public class Profile
{
    private Profile() { }
    private Profile(ProfileId id, UserId userId, Account account)
    {
        Id = id;
        UserId = userId;
        Account = account;
    }

    public ProfileId Id { get; private set; }
    public UserId UserId { get; private set; }
    public Account Account { get; private set; }
}

public class Account
{
    private Account() { }
    private Account(AccountId id, string name)
    {
        Id = id;
        Name = name;
    }

    public AccountId Id { get; private set; }
    public string Name { get; private set; }
    private readonly List<Profile> _profiles = new();
    public IReadOnlyCollection<Profile> Profiles =>_profiles.AsReadOnly();
}

This is the code for the Profile entity type configuration:

        builder.ToTable("profiles");
        builder.HasOne(profile => profile.Account)
            .WithMany(account => account.Members)
            .HasForeignKey("account_id")
            .IsRequired();
        builder.Property(profile => profile.UserId)
            .HasColumnName("user_id")
            .IsRequired();
        builder.HasKey("user_id", "account_id");

… and this is the one for Account:

        builder.ToTable("accounts");
        builder.HasKey(account => account.Id);

I want a composite key for the table Profile on “user_id” and “account_id”, but EF gives me this error.

Unable to create a ‘DbContext’ of type ‘AppDbContext’. The exception ‘The property ‘user_id’ cannot be added to the type ‘Profile’ because no property type was specified, and there is no corresponding CLR property or field. To add a shadow state property, the property type must be specified.’ was thrown while attempting to create an instance.

How can you configure the Profile entity with EF to achieve this goal?

LEAVE A COMMENT