0

I'm trying to create an EF model based on an existing MySQL Database. Upon creating an entity, I map it using:

[Table("databaseName.tableName")] or :

modelBuilder.Entity<Lang>().ToTable("tableName") in OnModelCreating.

The issue I have is that the table names could have an unexpected prefix. What I want to do is, without knowing the prefix, search for any table in the database that:

(Something like)EndsWith("tableName") use it, or:

which name matches a Regex.

Is this doable? The alternative would be to ask the user for the TablePrefix specific to his/her database and work with it (modelBuilder.Entity<Lang>().ToTable(prefix + "tableName") but that would be quite inconvenient. Since the prefix is the only thing that can change from database to an other, it would be really helpful to be able to detect tables by their name.

alozzi
  • 53
  • 4

1 Answers1

1

You can't query the database in OnModelCreating, but you can use the Connection String to open an ADO.NET Connection to the database and run a query to retrieve the table names and construct a mapping between the Entity types and the table names.

David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67
  • 1
    Thank you very much! I wish there was a built in functionality that allows string matching for table names or even properties. But that will do. I ended up creating an additional DbContext solely for executing `tableNamesModel.Database.SqlQuery("show tables from dbName")` in the `OnModelCreating` of the main Entity Model, and then select the tables I need regadless of the prefixes. Thank you for pointing me into the right direction. – alozzi May 28 '20 at 19:03