エンティティのジェネリック構成クラスを作成しようとしていますが、行き詰まります。
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
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加