Can anybody tell me how I can get the current database provider at line 9? So it can generated the migration correctly for the MySQL migrations. How do I do this the clean way.
1 internal class GroupConfiguration : IEntityTypeConfiguration<Group>
2 {
3 public void Configure(EntityTypeBuilder<Group> builder)
4 {
5 builder.ToTable(nameof(Group));
6 builder.HasKey("Id");
7 builder.Property(u => u.Id)
8 .ValueGeneratedOnAdd()
9 .HasDefaultValueSql((database.IsMySql()) ? "uuid()" : "newsequentialid()");
...
I'm using .NET Core 3.1, and my webapp supports multiple database providers. For now MySQL (Pomelo) and SQL Server. I need it to generate the migration the correct way. So I have a MySQL and SQL Server migrations.
But I don't want to update the MySQL generated migration manually.
The trick is to pass the DatabaseFacade
to your configuration class:
internal class GroupConfiguration : IEntityTypeConfiguration<Group>
{
private readonly DatabaseFacade _database;
public GroupConfiguration(DatabaseFacade database)
{
_database = database;
}
public void Configure(EntityTypeBuilder<Group> builder)
{
builder.ToTable(nameof(Group));
builder.HasKey("Id");
builder.Property(u => u.Id)
.ValueGeneratedOnAdd()
.HasDefaultValueSql((_database.IsMySql()) ? "uuid()" : newsequentialid()");
...
And then pass the Database
property in OnModelCreating
:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// ...
modelBuilder.ApplyConfiguration(new GroupConfiguration(Database));
// ...
}
Keep in mind that the configuration class can no longer be created by modelBuilder.ApplyConfigurationsFromAssembly()
, so you have to add the configuration with modelBuilder.ApplyConfiguration()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With