我有一个包含名称为 IdCard
的值对象的实体,如下所示:
public class UserProfile : BaseEntity<long>
{
public byte Gender { get; private set; } = 0;
public int? BirthDate { get; private set; }
public IdCard IdCard { get; set; }
}
和 IdCard
成员如下:
public class IdCard : ValueObject
{
public int? Type { get; set; }
public string No { get; set; }
}
我需要使用 EF Fluent api 将 IdCard No
作为索引
像这样的事情
builder.HasIndex(c => c.IdCard.No);
最佳答案
看看Implement value objects来自 Microsoft 和 Using Value Objects with Entity Framework Core链接。这两个很有帮助。
您可以创建UserProfileConfiguration
类,如下所示:
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);
}
}
然后,将其应用到 DbContext
中的 OnModelCreating
方法中:
modelBuilder.ApplyConfiguration(new UserProfileConfiguration());
关于c# - 如何使用 C# EF Fluent api 为值对象成员创建索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70025026/