Use ASP. Net MVC to connect MySQL and Code First, mvcmysql
First, prepare the tool as the Environment
- MySQL Community Server 5.7.x
- My Workbench 6.3
- VS2017
Create a project, NetMySQLCodeFirst
Select MVC, and then select no user verification
Then install the three packages through the NuGet Package Manager and install the latest stable version.
- EntityFramework
- MySql. Data
- MySql. Data. Entity
Next, create a new class Lexan in the Models file.
public Guid LexanID { get; set; } public string LexanName { get; set; } public int LexanAge { get; set; } public string LexanImage { get; set;
Create a Category in the Models file.
public Guid CategoryID { get; set; } public string CategoryName { get; set; }
Continue to create a CodeFirstContext class in the Models File
public DbSet<Lexan> Lexans { get; set; }public DbSet<Category> Categories { get; set; }
Modify the Web. config file, and in the system. add the following code before the web tag to indicate connection. net to connect to the MySQL string. The password is your own root login password, which can be modified according to the actual situation.
<connectionStrings> <add name="CodeFirstContext" connectionString="Data Source=localhost;port=3306; Initial Catalog=LexanCodeFirstDB;uid=root; pwd=******" providerName="MySql.Data.MySqlClient" /></connectionStrings>
After completing the above work, the next job is to go to the NuGet console, the connection settings after updating our database code are implemented. We have enabled the database name through LexanCodeFirstDb and will add a new migration. To this end, we use the Software Package Manager Console. Run the following command on the console:
enable-migrations
When the enable-migrations command is executed, the Migrations folder is automatically generated in the project, and then the Configuration method in the Configuration class is modified in the folder to add the following code.
AutomaticMigrationsEnabled = true; SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
Enter the code in the NuGet console to execute data migration. A prompt is displayed, indicating that the name is different from the project name.
add-migration
Mysql database engine code end uses the default structure, the primary key will also return this error for the mentioned area. As a solution, we will upgrade our context model as follows. Previously, similar to the SqlGenerator we set above, and then modify the codeFirstContext class, as shown below:
Continue to execute the following code on the NuGet console to update the database
update-database
Here we have completed all our work. Let's see if MySQL Data is not migrated.
Let's take a look at the database after the money
Successful!