EF CORE Fluent Api La configurazione in file separati sta funzionando bene con le classi semplici Ref # 1 && Ref # 2 . Il problema si presenta quando le entità sono ereditate da KeyedEntity
o AuditableEntity
class abstract KeyedEntity<TValue> {
public TValue Id {get; set;}
}
class abstract AuditableEntity<TValue> : KeyedEntityBase<TValue>{
public DateTime DateCreated {get; set;}
public DateTime DateModified {get; set;}
}
Mapper va in questo modo
public class KeyedEntityMap<TEntity, TId>
: IEntityTypeConfiguration<TEntity> where TEntity
: KeyedEntityBase<TId> where TId : struct
{
public void Configure(EntityTypeBuilder<TEntity> builder)
{
// Primary Key
builder.HasKey(t => t.Id);
// Properties
builder.Property(t => t.Id).HasColumnName("id").ValueGeneratedOnAdd();
}
}
public class AuditableEntityMap<TEntity, TId>
: IEntityTypeConfiguration<TEntity> where TEntity
: AuditableEntity<TId> where TId : struct
{
public void Configure(EntityTypeBuilder<TEntity> builder)
{
// Properties
builder.Property(t => t.DateCreated).HasColumnName("DateCreated");
builder.Property(t => t.DateModified).HasColumnName("DateModified");
}
}
Ora il problema si verifica con l'entità che eredita da AuditableEntity
. Ho bisogno di registrarsi Map da quella classe Enitity particolare lungo con AuditableEntityMap
di classe e KeyedEntityMap
di classe.
Ora posso anche dimenticare di Map Inheritance e unire tutte le mappe di eredità complesse nella classe entity, che non voglio fare e rispettare DRY . Il problema con l'eredità complessa è che non sta registrando le mie mappe di entità
Esistono diversi modi per ottenere DRY per la configurazione dell'entità di base.
Bit il più vicino al tuo progetto attuale è semplicemente seguire la gerarchia delle entità nelle classi di configurazione:
public class KeyedEntityMap<TEntity, TId> : IEntityTypeConfiguration<TEntity>
where TEntity : KeyedEntityBase<TId>
where TId : struct
{
public virtual void Configure(EntityTypeBuilder<TEntity> builder)
// ^^^
{
// Primary Key
builder.HasKey(t => t.Id);
// Properties
builder.Property(t => t.Id).HasColumnName("id").ValueGeneratedOnAdd();
}
}
public class AuditableEntityMap<TEntity, TId> : KeyedEntityMap<TEntity, TId>
// ^^^
where TEntity : AuditableEntity<TId>
where TId : struct
{
public override void Configure(EntityTypeBuilder<TEntity> builder)
// ^^^
{
base.Configure(builder); // <<<
// Properties
builder.Property(t => t.DateCreated).HasColumnName("DateCreated");
builder.Property(t => t.DateModified).HasColumnName("DateModified");
}
}
e quindi per un'entità specifica che richiede una configurazione aggiuntiva:
public class Person : AuditableEntity<int>
{
public string Name { get; set; }
}
dovresti registrarti
public class PersonEntityMap : AuditableEntityMap<Person, int>
{
public override void Configure(EntityTypeBuilder<Person> builder)
{
base.Configure(builder);
// Properties
builder.Property(t => t.Name).IsRequired();
// etc...
}
}