@David Thielen, you could try the following two methods to use fluent api to make a column pair unique.
First of all, we need to make some changes in my class:
Then, we could use the following two methods to do it.
public class County
{
public int Id { get; set; }
[Key]
[Column(Order = 0)]
public string? Name { get; set; }
[Key]
[Column(Order = 1)]
public int StateId { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//modelBuilder.Entity<County>().HasKey(x => new { x.Name, x.StateId }); //First method
modelBuilder.Entity<County>().HasIndex(x => new { x.Name, x.StateId }).IsUnique(); // Second method
}
Also, to verify, Id will remain the primary key - correct?
No, based on my test, Id is not the primary key.
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.