1. Introduction
Encounter a problem at work. The project has three databases (three database table structures), and the user can choose which database to use. is actually the dynamic switch database connection.
2.EntityFramework for Mysql
Let's start with a simple introduction to MySQL using EntityFramework to manipulate the database.
Directly on the code:
(1). Build a project first, install Mysql,entityframework related package
(2). Establishing entities and corresponding database tables
(3). Writing a database connection string, writing a context entity
This allows you to use EntityFramework to access MySQL data.
(4). Simple test
3. Dynamically switch Databases (1). Building a BLOG1 database, a table such as a blog database.
(2). Modification of the context
(3). Retrofit test
4. Why the link string can be passed directly
The method signature from the DbContext constructor can be discerned.
It can be seen that we pass the database connection string names and direct database connection strings are all possible. EntityFramework will make the judgment, if it is name, then go to configure the file to fetch the database connection string and providername. If it is a database connection string, use it directly.
5. The pits encountered
In fact, entityframework support for MySQL is not very good, there are some bugs. I ran into a problem when I was doing the above experiment. When I passed the database connection string directly to the constructor of the parent class, I reported: Keyword not supported: ' Port ' error. After some searching, we found three solutions: Https://stackoverflow.com/questions/45217166/c-sharp-entity-framework-keyword-not-supported-port.
Children's shoes that meet the pit can go and see.
EntityFramework for Mysql dynamic switch data source