[Ef]vs15+ef6+mysql Code First mode

Source: Internet
Author: User

Write in front

In front of an article, tried the db first way, but do not know what the reason has not been successful, to the end is not resolved, today try the way code first.

[Ef]vs15+ef6+mysql This question, have you ever met?

An example

Steps

    1. Mysql-for-visualstudio-1.2.4.msi download the file, and then run the installation (if it is not installed, install it first).
    2. Connector/net Download the file and install it (if it is not installed, please install it first)
    3. Installing EF with NuGet
    4. Use the NuGet provider.

After the above steps are complete, modify the Web. config file as follows:

<?XML version= "1.0" encoding= "Utf-8"?><Configuration>  <configsections>    <!--for more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -    < Sectionname= "EntityFramework"type= "System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, version=6.0.0.0, culture= Neutral, publickeytoken=b77a5c561934e089 "requirepermission= "false" />  </configsections>  <Startup>    <supportedruntimeversion= "v4.0"SKU=". netframework,version=v4.5.2 " />  </Startup>  <EntityFrameworkCodeconfigurationtype= "MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">    <defaultconnectionfactorytype= "System.Data.Entity.Infrastructure.LocalDbConnectionFactory, entityframework">      <Parameters>        <parametervalue= "Mssqllocaldb" />      </Parameters>    </defaultconnectionfactory>    <providers>      <providerInvariantName= "MySql.Data.MySqlClient"type= "MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6, version=6.9.7.0, Culture=neutral, Publickeytoken=c5687fc88969c44d " />    </providers>  </EntityFramework>  <System.Data>    <dbproviderfactories>      <Removeinvariant= "MySql.Data.MySqlClient" />      <Addname= "MySQL Data Provider"invariant= "MySql.Data.MySqlClient"Description= ". Net Framework Data Provider for MySQL"type= "MySql.Data.MySqlClient.MySqlClientFactory, Mysql.data, version=6.9.7.0, Culture=neutral, publickeytoken= C5687fc88969c44d " />    </dbproviderfactories>  </System.Data>  <connectionStrings>    <Addname= "Mycontext"connectionString= "Data source=localhost;port=3306;initial catalog=myshop;user id=sa;password=sa;"ProviderName= "MySql.Data.MySqlClient"/>  </connectionStrings></Configuration>

Note the EntityFramework node, which is not the default Codeconfigurationtype property, is added. Otherwise, the following error will occur: Specified key was too long; Max key length is 767 bytes

Test

Entity class

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel.DataAnnotations;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacewolfy.ef_mysql_codefirst{ Public classProduct { Public intId {Set;Get; } [MaxLength ( -)]         Public stringName {Set;Get; } [MaxLength ( -)]         Public stringCategory {Set;Get; }  Public decimalPrice {Set;Get; }  PublicDateTime CreateDate {Set;Get; } }}

Inserting information

usingSystem;usingSystem.Collections.Generic;usingSystem.Data.Entity;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacewolfy.ef_mysql_codefirst{classProgram {Static voidMain (string[] args) {            varDbContext =NewMycontext (); Idatabaseinitializer<MyContext> Dbinitializer =NULL; if(DbContext.Database.Exists ()) {//if the database already existsDbinitializer =NewDropcreatedatabaseifmodelchanges<mycontext>(); }            Else            {                //always first delete and then createDbinitializer =NewDropcreatedatabasealways<mycontext>(); }//database.setinitializer (Dbinitializer);
Dbinitializer.initializedatabase (DbContext); DBCONTEXT.PRODUCTS.ADD (NewProduct () {createdate = DateTime.Now.AddDays (1), Name ="nan Fu Battery", Category ="Daily Necessities", Price =3 }); Dbcontext.savechanges (); } }}

There is another mistake that often occurs

Model compatibility cannot is checked because the database does not contain model metadata. Model compatibility can only is checked for databases created using code first or Code first migrations.

The general idea is that the compatibility of the model cannot be checked because the database does not contain model metadata. The compatibility of the model needs to be checked when using code first or code FISRT for database creation.

At this point, although table _migrationhistory is generated, the table contents are empty.

This time the database can be deleted and regenerated to be resolved.

Where table _migrationhistory is the creation history table.

Products table

Found that the added data in Chinese is garbled, this is because the MySQL default character set is Latin

There are many solutions to garbled characters, you can modify the character set of the database, or the character set of the data table. You can also modify the connection string as follows:

  < connectionStrings >    <  name= "mycontext"  connectionString= "Data source=localhost;port=3306;i Nitial catalog=myshop;user Id=sa;password=sa;charset=utf8 "  providerName=" MySql.Data.MySqlClient "/>  </connectionStrings>

Summarize

Tossing the whole morning, a simple demo came out.

[Ef]vs15+ef6+mysql Code First mode

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.