【问题标题】:Generic entity configuration class in EF Core 2EF Core 2 中的通用实体配置类
【发布时间】:2018-06-04 11:06:16
【问题描述】:

我正在尝试为我的实体创建一个通用配置类,但我被卡住了。

我有一个名为 EntityBase 的抽象类:

public abstract class EntityBase
{
    public int Id { get; set; }
    public int TenantId { get; set; }
    public DateTime CreatedOn { get; set; }
    public DateTime UpdatedOn { get; set; }
}

还有许多其他从 EntityBase 继承的类,我必须在每个类中使用相同的代码配置 DateTime 属性。这样:

void EntityTypeConfiguration<MyEntity>.Configure(EntityTypeBuilder<MyEntity> builder)
    {
        builder.HasIndex(e => e.TenantId);
        builder.Property(e => e.CreatedOn)
              .ValueGeneratedOnAdd()
              .HasDefaultValueSql("GETDATE()");

        // Other specific configurations here
    }

我希望能够调用类似:builder.ConfigureBase() 并避免代码重复。有什么想法吗?

【问题讨论】:

  • 这纯粹是为了设置一个默认值还是这个场景更像是“在插入/编辑时自动设置这些值”?
  • 只是将 TenantId 配置为索引并设置 CreatedOn 属性的默认值

标签: c# entity-framework-core ef-core-2.0


【解决方案1】:

有几种方法可以实现目标。例如,由于您似乎正在使用IEntityTypeConfiguration&lt;TEntity&gt; 类,您可以使用virtual void Configure 方法创建一个基本的通用配置类,并让您的具体配置类从它继承,覆盖Configure 方法并在执行之前调用base.Configure他们的具体调整。

但是假设您希望能够准确地调用builder.ConfigureBase()。要允许这种语法,您可以简单地将通用代码移动到自定义的通用扩展方法,如下所示:

public static class EntityBaseConfiguration
{
    public static void ConfigureBase<TEntity>(this EntityTypeBuilder<TEntity> builder)
        where TEntity : EntityBase
    {
        builder.HasIndex(e => e.TenantId);
        builder.Property(e => e.CreatedOn)
              .ValueGeneratedOnAdd()
              .HasDefaultValueSql("GETDATE()");

    }
}

使用示例:

void IEntityTypeConfiguration<MyEntity>.Configure(EntityTypeBuilder<MyEntity> builder)
{
    builder.ConfigureBase();
    // Other specific configurations here
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 2023-02-04
    相关资源
    最近更新 更多