MyDaftQuestions
MyDaftQuestions

Reputation: 4691

Can I add a primary key and a unique constraint in EFCore

I'm manually moving from .NET Framework to .NET Core and working on the EF and DTOs.

I'm not enjoying this - I have read indexes are not supported via annotation and as such, am currently mixing fluent api and annotations which is a code smell. However, it appears as if I must proceed with this combination.

My question is if I can achieve this only with fluent api. My table has both a primary key and a unique constraints.

My object looks like

class Person
{
    public int Id {get;set;}
    public string UniqueToken {get;set;}
}

However, I am unable to add the following

modelBuilder.Entity<Person>()
            .HasKey(a => a.Id)
            .HasIndex(a => a.UniqueToken).IsUnique();  //this is what I would like to add but I can't.

I've attempted something which feels like a hacky work around

modelBuilder.Entity<Person>()
            .HasKey(a => a.Id);

modelBuilder.Entity<Person>()
            .HasIndex(a => a.UniqueToken).IsUnique();  

Again, adding this entry twice seems a little bleugh… Fluent appears to want to simply chain the methods.

I have read on this, but I'm getting very lost. Is it possible to add both the primary key and unique constraint ?

Upvotes: 1

Views: 1954

Answers (1)

TanvirArjel
TanvirArjel

Reputation: 32059

Better you separate your entity configurations from OnModelCreating method with IEntityTypeConfiguration interface as follows:

public class PersonConfiguration : IEntityTypeConfiguration<Person>
{
    public void Configure(EntityTypeBuilder<Person> builder)
    {
        builder.HasKey(a => a.Id);
        builder.HasIndex(a => a.UniqueToken).IsUnique();
    }
}

Now you can add configuration for all of your Db entities like PersonConfiguration and register all of them at once as follows:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.ApplyConfigurationsFromAssembly(typeof(PersonConfiguration).Assembly);
}

This will give you more separation of concern and readability!

Upvotes: 5

Related Questions