Entity Framework 中基础实体的流畅配置

Fluent configuration for base entity in Entity Framework

我有以下 BaseEntity

public class BaseEntity
{
    public BaseEntity()
    {
        DateCreated = DateTime.UtcNow;
        DateModified = DateTime.UtcNow;
    }

    public DateTime DateCreated { get; set; }
    public DateTime DateModified { get; set; }

    [MaxLength(36)]
    public string CreateUserId { get; set; }

    [MaxLength(36)]
    public string ModifyUserId { get; set; }
}

我所有的其他实体都来自它。现在我想使用流畅的配置而不是 DataAnnotations。我真的必须在每个 DbModelBuilder 配置中配置两个字符串属性的 MaxLength 吗?

Do I really have to configure the MaxLength of the two string properties in every single DbModelBuilder configuration?

没有。您可以配置基类型验证,EF 会将它们应用于派生类型。例如:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<BaseEntity>().Property(x => x.CreateUserId).HasMaxLength(36);
    modelBuilder.Entity<BaseEntity>().Property(x => x.ModifyUserId).HasMaxLength(36);

    base.OnModelCreating(modelBuilder);
}

更新(根据您的评论):

您可以使用(相当新的)Properties() 方法来定义基于 属性 名称而不是实体类型的映射和验证。

例如:

modelBuilder.Properties().Where(x => x.Name == "CreateUserId").Configure(x => x.HasMaxLength(36));
modelBuilder.Properties().Where(x => x.Name == "ModifyUserId").Configure(x => x.HasMaxLength(36));

MSDN