In EF6 è stato possibile definire convenzioni basate su tipi di proprietà durante la costruzione del modello, come ad esempio ...
public interface IEntity
{
Guid Id { get; }
}
public class MyEntity : IEntity
{
public Guid Id { get; set; }
}
public class MyDbContext : DbContext
{
public override void OnModelCreating(DbModelBuilder builder)
{
builder
.Properties<Guid>()
.Where(x => x.Name == nameof(IEntity.Id)
.Configure(a=>a.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity));
}
}
Questo approccio potrebbe anche essere utilizzato per impostare la lunghezza della stringa predefinita / nullità e così via.
Ho esaminato il modello di base EF e i tipi associati e non trovo alcun modo di applicare una convenzione equivalente in un modo che è stato emanato dal generatore di migrazione o che non impedisce al generatore di migrazione di rifiutare del tutto il modello. Questo è del tutto frustrante e sembra regressivo.
Aggiornare
Aggiunta di quanto segue all'evento OnModelCreating ...
foreach (var pb in builder.Model
.GetEntityTypes()
.Where(x=>typeof(IEntity).IsAssignableFrom(x.ClrType))
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(Guid) && p.Name == nameof(IEntity.Id))
.Select(p => builder.Entity(p.DeclaringEntityType.ClrType).Property(p.Name)))
{
pb.UseSqlServerIdentityColumn();
}
... produce il seguente messaggio su Add-Migration
Identity value generation cannot be used for the property 'Id' on entity type 'Tenant' because the property type is 'Guid'. Identity value generation can only be used with signed integer properties.
Questo fa il lavoro, ma è piuttosto inelegante.
foreach (PropertyBuilder pb in builder.Model
.GetEntityTypes()
.Where(x=>typeof(IEntity).IsAssignableFrom(x.ClrType))
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(Guid) && p.Name == nameof(IEntity.Id))
.Select(p => builder.Entity(p.DeclaringEntityType.ClrType).Property(p.Name)))
{
pb.ValueGeneratedOnAdd().HasDefaultValueSql("newsequentialid()");
}