Search code examples
c#domain-driven-designvalue-objects

how to create index for value-object member using c# EF fluent api


I have entity that contain value-object with name IdCard like this:

public class UserProfile : BaseEntity<long>
{
  public byte Gender { get; private set; } = 0;

  public int? BirthDate { get; private set; }

  public IdCard IdCard { get; set; }
}

And IdCard member like this:

public class IdCard : ValueObject
    {
        public int? Type { get; set; }

        public string No { get; set; }
    }

I need to make IdCard No as index by using EF fluent api

some thing like this

builder.HasIndex(c => c.IdCard.No);

Solution

  • Take a look at the Implement value objects from Microsoft and Using Value Objects with Entity Framework Core links. These two are helpful.

    You can create UserProfileConfiguration class as follow:

    public class UserProfileConfiguration : IEntityTypeConfiguration<UserProfile>
    {
        public void Configure(EntityTypeBuilder<UserProfile> builder)
        {
            builder.HasKey(x => x.Id);
            builder.OwnsOne(x => x.IdCard);
            builder.HasIndex(x => x.No);
        }
    }
    

    And then, apply it in OnModelCreating method in your DbContext:

    modelBuilder.ApplyConfiguration(new UserProfileConfiguration());