将EF CORE Fluent Api配置在单独的文件中,对于简单类Ref #1和Ref #2可以正常工作。问题出现在实体继承自KeyedEntity
或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;}
}
映射器大致如下
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");
}
}
现在问题出现在继承自的实体上。我需要注册该特定实体类的映射,以及类和类。现在,我可以忘记映射继承,并将所有复杂的继承映射合并到实体类中,但我不想这样做,而是遵循DRY原则。复杂继承的问题在于它无法注册我的实体映射。
TId
。我希望在添加ValueGeneratedOnAdd
时生成一个Guid
值,但如果它是一个int
,我想使用UseIdentityColumn
方法。 - liqSTARif (typeof(TId) == typeof(Guid)) builder.Property(t => t.Id).ValueGeneratedOnAdd(); else if (..) else ...
等等。 - Ivan Stoev