c# - 如何使用 C# EF Fluent api 为值对象成员创建索引

标签 c# domain-driven-design value-objects

我有一个包含名称为 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/

相关文章:

c# - 从 CngKey 或 X509Certificate(2) 实例生成 CSR

java - BPEL 与领域事件集成多个有界上下文

ios - 在 iOS 核心数据中映射嵌入式对象

php - 什么是 PHP 中值对象的示例?

c# - 从返回 View 模型的 Controller 操作加载 View 时为空字段

c# - 为什么在使用 Prism EventAggregator 时没有调用我的订阅方法?

linq-to-sql - ASP.MVC : Repository that reflects IQueryable but not Linq to SQL, DDD 如何提问

design-patterns - 您如何在领域驱动设计中使用具有工厂模式的接口(interface)?

c# - 仅当不记名 header 存在时才验证 JWT