繁体   English   中英

EF Core 2中的通用实体配置类

[英]Generic entity configuration class in EF Core 2

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

我有一个名为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()的东西并避免代码重复。 有任何想法吗?

有几种方法可以实现目标。 例如,由于您似乎正在使用IEntityTypeConfiguration<TEntity>类,您可以使用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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM