Entity Framework Core 7 - configuring two keys

49 Views Asked by At

I have the following entities:

public class Account : Entity
{
    // ...
    public long RoleID { get; set; }
    public Role Role { get; set; }
}

public class Role : Entity
{
    // ...
}

public abstract class Entity
{
    public long ID { get; set; }
    public string? UUID { get; set; }
    // ...
}

Initially, I am trying to perform an update on an entity based on the UUID column instead of the ID, but I do not want to have to fetch the entity and then perform the update. I know that EF Core needs the primary key to track and update the entity, but is there a way to configure it to use another property?

In a second attempt, I tried to make the UUID become the primary key and configured the ID column as a secondary key using HasAlternateKey because I want the ID column to still be used for relationships between entities.

I configured it as follows:

modelBuilder.Entity<Account>
(
    e => e.HasOne(a => a.Role)
          .WithMany()
          .HasForeignKey(a => a.RoleID)
);
modelBuilder.Entity<Account>
(
    e => e.HasKey(a => a.UUID)
);
modelBuilder.Entity<Role>
(
    e => e.HasAlternateKey(r => r.ID)       
);

The goal was to maintain the relationship being made by the ID column, but the following error ends up being thrown:

The relationship from 'Account.Role' to 'Role' with foreign key properties {'RoleID' : long} cannot target the primary key {'UUID' : string} because it is not compatible. Configure a principal key or a set of foreign key properties with compatible types for this relationship.

0

There are 0 best solutions below