The first thing to do is to prepare the tool as an environment
- MySQL Community Server 5.7.x
- My Workbench 6.3
- VS2017
Create a new project, Netmysqlcodefirst
Select MVC, and then select No user authentication
Then install three packages through the NuGet Package Manager and install the latest stable version
- EntityFramework
- Mysql.data
- MySql.Data.Entity
Next, create a new class in the models file Lexan
Public Get Set ; } Public string Get Set ; } Public int Get Set ; } Public string Get Set
and continue to build a category in the models file.
Public Get Set ; } Public string Get set; }
Continue to build a class in the models file Codefirstcontext
Public Get Set ; } Public Get set; }
Modify the Web. config file under the root directory and add the following code in front of the system.web label to indicate the connection. Net connection MySQL string, password is the login password of your root, modify 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 doing the work above, the next thing to do is to go to the NuGet console, update our database code after the connection settings to implement our database name through LEXANCODEFIRSTDB is enabled and will add a new migration. To do this, we use the Package Manager console. Execute the following command in the console
Enable-migrations
At this time because the enable-migrations command is executed, the project will automatically generate the Migrations folder, and then go to this folder to modify the configuration method inside the class, add the following code
true ; Setsqlgenerator ("MySql.Data.MySqlClient"new MySql.Data.Entity.MySqlMigrationSqlGenerator ());
Continue to enter the code in the NuGet console, do the data migration, prompted to enter the name, the name and the project name is different
Add-migration
MySQL's database engine code side uses the structure that is created by default, and the primary key also returns this error for the area mentioned. As this solution, we will upgrade our context model again as follows. Previously, similar to the sqlgenerator we set above, and then go to modify the Codefirstcontext class, as shown below
Continue to update the database in the NuGet console by executing the following code
Update-database
All of our work is done here and we look at the MySQL data when there is no migration
And look at the database after the money.
It worked!
ASP. NET MVC connection MySQL and code first use