MySQL CodeFirst configuration and precautions, mysqlcodefirst

Source: Internet
Author: User

MySQL CodeFirst configuration and precautions, mysqlcodefirst

The configuration of mysql + ef is more complex than that of mssql + ef. I feel that the configuration difficulty lies in the various incompatibility problems caused by the plug-in version. In addition, I have referenced many blogs to integrate the experiences of Multiple blogs, because not everyone's operations are the same as those described by those bloggers. However, after the solution, I would like to explain it to others. Now I am operating mysql + CodeFirst from scratch, and summarize my configuration process. Make sure that the mysql database is installed and enabled:

1. Create a console Project

2. Install the SDK In the Package Manager Console in sequence.(Note: The EF version must be low. In addition, version ② and ③ must be consistent. Because ③ and ② are dependent, version inconsistency may cause some problems)
① Install-Package EntityFramework-Version 6.1.3

② Install-Package MySql. Data-Version 6.8.8

③ Install-Package MySql. Data. Entity-Version 6.8.8

3. Add the following in the App. Config configuration file:

<connectionStrings><add name="connStr" connectionString="data source=127.0.0.1;user id=root;password=123456;database=sqltest;" providerName="MySql.Data.MySqlClient" /></connectionStrings>

4. Create the Person object class and the PersonConfig class in sequence. The detailed code is as follows:

public class Person    {        public int Id { get; set; }        public string Name { get; set; }        public int Age { get; set; }    }

 

class PersonConfig : EntityTypeConfiguration<Person>    {        public PersonConfig()        {            this.ToTable("T_Persons");        }    }

5. Create a New MyContext class with detailed code(Note: If you do not mark DBConfigurationType above the class, an error will occur during the final update-database operation. Do not forget):

[DbConfigurationType (typeof (MySql. data. entity. mySqlEFConfiguration)] class MyContext: DbContext {public MyContext (): base ("name = connStr ") // name corresponds to the connection string name attribute {} public DbSet <Person> Persons {get; set;} protected override void OnModelCreating (DbModelBuilder modelBuilder) {base. onModelCreating (modelBuilder); modelBuilder. events. addFromAssembly (Assembly. getExecutingAssembly ());}}

6. continue to run the command Enable-Migrations-force on the Package Manager Console. After the command is successful, the message will appear:

Note: A folder and a class are automatically generated under the project ,:

7. Open Configuration. cs, change the value of AutomaticMigrationsEnabled to true, and run the update-database-force command on the Package Manager Console. The message will appear after the operation is successful:

NOTE: If DBConfigurationType is not marked above the MyContext class, this step is wasted for several hours, and No MigrationSqlGenerator found for provider 'mysql will be displayed. data. mySqlClient '. use the SetSqlGenerator method in the target migrations configuration class to register additional SQL generators.

8. Now let's test the effect. Currently, mysql does not have a database named sqltest, and CodeFirst automatically generates a database through code. The main function code is as follows:

Using (MyContext ctx = new MyContext () {Person per1 = new Person {Name = "per1", Age = 12}; Person per2 = new Person {Name = "per2 ", age = 17}; Person per3 = new Person {Name = "per3", Age = 19}; ctx. persons. add (per1); ctx. persons. add (per2); ctx. persons. add (per3); ctx. saveChanges (); Console. writeLine ("successfully added");} Console. readKey ();

9. If it succeeds after running, refresh the Database List of Navicat for MySQL to find the newly generated database:

Note: ① The _ migrationhistory table is automatically generated, indicating that the configuration is successful. ② This. ToTable ("T_Persons") in PersonConfig. cs; the table name after successful ing of object classes. ③ The default Id field is the primary key and auto-increment. Therefore, you do not need to manually assign values to the Id attribute.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.