Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine database provider at the IEntityTypeConfiguration, because I support multiple databases

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.

like image 215
Christiaan Avatar asked Oct 18 '25 13:10

Christiaan


1 Answers

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().

like image 50
Christian Held Avatar answered Oct 21 '25 04:10

Christian Held