简体   繁体   English

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

[英]Generic entity configuration class in EF Core 2

I'm trying to create a generic configuration class for my entities but i'm stuck. 我正在尝试为我的实体创建一个通用配置类,但我被卡住了。

I have an abstract class called EntityBase: 我有一个名为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; }
}

And many other classes that inherit from EntityBase, in which i have to configure the DateTime properties in each one with the same code. 还有许多继承自EntityBase的类,其中我必须使用相同的代码在每个类中配置DateTime属性。 This way: 这条路:

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

        // Other specific configurations here
    }

I would like to be able to call somthing like: builder.ConfigureBase() and avoid the code duplication. 我希望能够调用类似于:builder.ConfigureBase()的东西并避免代码重复。 Any ideas? 有任何想法吗?

There are several way you can accomplish the goal. 有几种方法可以实现目标。 For instance, since you seem to be using IEntityTypeConfiguration<TEntity> classes, you could create a base generic configuration class with virtual void Configure method and let your concrete configuration classes inherit from it, override the Configure method and call base.Configure before doing their specific adjustments. 例如,由于您似乎正在使用IEntityTypeConfiguration<TEntity>类,您可以使用virtual void Configure方法创建基本通用配置类,并让您的具体配置类继承它,覆盖Configure方法并调用base.Configure然后再执行它们的操作。具体调整。

But let say you want to be able to exactly call builder.ConfigureBase() . 但是,假设您希望能够准确地调用builder.ConfigureBase() To allow that syntax, you can simply move the common code to a custom generic extension method like this: 要允许该语法,您只需将公共代码移动到自定义通用扩展方法,如下所示:

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()");

    }
}

with sample usage: 样本用法:

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