EF6 Codefirst+mysql Database Migration

Source: Internet
Author: User
Tags mysql for visual studio

Brief introduction

The project uses MSSQL as a database, but because the SQL Server is a bit more expensive and the concurrency connection is a little bit worse, migrating data to MySQL, incidentally, and the problem. Environment

· Visual Studio 2013

· MySQL 5.7

· Entity Framework 6.1.3 Body Migration process

1. Install MySQL, incidentally install MySQL for Visual Studio, MySQL Connector Net

2. Add a NuGet package to the Entity Framework Project and the website project. MySql.Data.Entity, I added here is the 6.9.6 version, add the Mysql.data as a dependency after adding to the project, you can see that after completing the Web. config and app. Config added MySQL Provider and Dbprovidefactories.

<EntityFramework>    <defaultconnectionfactorytype= "System.Data.Entity.Infrastructure.LocalDbConnectionFactory, entityframework">      <Parameters>        <parametervalue= "v11.0" />      </Parameters>    </defaultconnectionfactory>    <providers>      <providerInvariantName= "System.Data.SqlClient"type= "System.Data.Entity.SqlServer.SqlProviderServices, entityframework.sqlserver" />       <provider  invariantname= "MySql.Data.MySqlClient"  type= "MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, version=6.9.9 .0, Culture=neutral, publickeytoken=c5687fc88969c44d "></provider>     </providers>  </EntityFramework>
<System.Data>    <dbproviderfactories>       <Remove  invariant= "MySql.Data.MySqlClient" /><  Add  name= "MySQL Data Provider"  invariant= " MySql.Data.MySqlClient "  description=". Net Framework Data Provider for MySQL "  type= "MySql.Data.MySqlClient.MySqlClientFactory, Mysql.data, version=6.9.9.0, culture=neutral , publickeytoken=c5687fc88969c44d " />     </dbproviderfactories>  </System.Data>

3. Modify the connection string for Web. config, providername modified to: MySql.Data.MySqlClient.

<name= "DefaultConnection"  providerName= "  MySql.Data.MySqlClient"  connectionString=" Data source=127.0.0.1;initial Catalog=demo; User Id=root; Password=root "/>

4. Back to the EntityFramework project, locate the DbContext class and add properties for the class: [Dbconfigurationtype (typeof (MySql.Data.Entity.MySqlEFConfiguration) )]

   [Dbconfigurationtype (typeof (MySql.Data.Entity.MySqlEFConfiguration))] Public classMydbcontext:dbcontext {/// <summary>        ///set up database connections for data entities/// </summary>         PublicMydbcontext ():Base("defaultconnection")        {        }                //The onmodelcreating method must be overridden with the fluent API        protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {Base.            Onmodelcreating (ModelBuilder); ModelBuilder.Conventions.Remove<PluralizingTableNameConvention> ();//contract for removing plural table names        }    }

5. OK, these jobs are done, basically, open the Package Manager console, and then enter: Update-database

Migration process Issues

1. Object references are not set to an instance of the object.

Problem Description: This is a more general error hint, many errors will prompt this, the Internet to find some less right, the final discovery is because the startup item is set to the EF project, and the default project is also the EF project, because the config file is not caused by the connection string.

Solution: Add a connection string to the Ef App. Config, or the startup project is set to website.

2. Underlying provider does not support the type ' nvarchar (max) '.

Problem Description: Literally means that provider does not support type "nvarchar (max)", which is related to the data types supported by the MySQL database.

Solution: Find out if the entity definition has a String type, add properties such as: [Stringlength (1000)], and then solve the problem.

3. The provider did not return a providermanifesttoken string.

Problem reason: The connection string was incorrectly written.

Correct notation: Data source cannot be used.

<name= "DefaultConnection"  providerName= "MySql.Data.MySqlClient"  connectionString= "Data source=127.0.0.1; Initial Catalog=demo; User Id=root; Password=root "/>

4. Unresolved members "Mysql.data.mysqlclient.mysqlexception,mysql.data, version=6.9.9.0, Culture=neutral, PublicKeyT

System.Runtime.Serialization.SerializationException:  
unresolved members "Mysql.data.mysqlclient.mysqlexception,mysql.data, version=6.9.9.0, Culture=neutral, PublicKeyToken= The type of c5687fc88969c44d ". In System.AppDomain.DoCallBack (CrossAppDomainDelegate callbackdelegate) in System.Data.Entity.Migrations.Design.ToolingFacade.Run (Baserunner runner) in System.Data.Entity.Migrations.Design.ToolingFacade.Update (String targetmigration, Boolean Force) in System.Data.Entity.Migrations.UpdateDatabaseCommand. <>C__displayclass2. < . ctor >b__0 ()  in System.Data.Entity.Migrations.MigrationsDomainCommand.Execute (Action command)  
Unresolved members "Mysql.data.mysqlclient.mysqlexception,mysql.data, version=6.9.9.0, Culture=neutral, PublicKeyToken= The type of c5687fc88969c44d ".

Solution: Generally occurs from the original development environment to the new development environment, in the development environment, the lack of "mysql-connector-net" this thing, download and install.

5. Starting at index 0, the format of the initialization string does not conform to the specification.

Problem Description: This question is similar to the first one, except for a hint, because I have not set the item containing the connection string as the startup item in the project, resulting in a missing connection string in Webconfig.

pm> update-database Specifies the "-verbose" flag to view the SQL statements applied to the target database. System.ArgumentException: from the index0, the format of the initialization string does not conform to the specification. In System.Data.Common.DbConnectionOptions.GetKeyValuePair (StringConnectionString,Int32CurrentPosition, StringBuilder buffer, Boolean useodbcrules,String& KeyName,String& KeyValue) in System.Data.Common.DbConnectionOptions.ParseInternal (Hashtable parsetable,StringconnectionString, Boolean buildchain, Hashtable synonyms, Boolean firstkey) in System.Data.Common.DbConnectionOptio Ns.. ctor (StringconnectionString, Hashtable synonyms, Boolean useodbcrules) in System.Data.Common.DbConnectionStringBuilder.set_ ConnectionString (Stringvalue) in MySql.Data.MySqlClient.MySqlConnectionStringBuilder. ctor (Stringconnstr) in MySql.Data.MySqlClient.MySqlConnection.set_ConnectionString (Stringvalue) in MySql.Data.MySqlClient.MySqlConnection. ctor (StringconnectionString) in MySql.Data.Entity.MySqlConnectionFactory.CreateConnection (StringconnectionString) in System.Data.Entity.Internal.LazyInternalConnection.Initialize () in System.Data.Entity.Internal.LazyInternalConnection.get_Connection () in System.Data.Entity.Internal.LazyInternalContext.get_Connection () in System.Data.Entity.Infrastructure.DbContextInfo. ctor (Type contexttype, dbproviderinfo modelproviderinfo, AppConfig config, dbconnectioninfo connectioninfo, Func '1resolver) in System.Data.Entity.Migrations.DbMigrator. ctor (dbmigrationsconfiguration configuration, DbContext Userscontext, Databaseexistencestate existencestate, Boolean calledbycreatedatabase) in System.Data.Entity.Migrations.DbMigrator. ctor (Dbmigrationsconfiguration configuration) in System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.GetMigrator () in System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run () in System.AppDomain.DoCallBack ( CrossAppDomainDelegate callbackdelegate) in System.AppDomain.DoCallBack (CrossAppDomainDelegate callbackdelegate) in System.Data.Entity.Migrations.Design.ToolingFacade.Run (Baserunner runner) in System.Data.Entity.Migrations.Design.ToolingFacade.Update (Stringtargetmigration, Boolean Force) in System.data.entity.migrations.updatedatabasecommand.<>c__displayclass2 . <.ctor>b__0 () in System.Data.Entity.Migrations.MigrationsDomainCommand.Execute (Action command) from the index0, the format of the initialization string does not conform to the specification.

Solution: Set the project that contains the connection string as the startup Project , and the project that contains the DbContext as the default migration project, which is the default project in the package management console.

EF6 Codefirst+mysql Database Migration

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.