How to use Mysql in EF and frequently asked questions _mysql

Source: Internet
Author: User
Tags mysql in connectionstrings

Sometimes need to rent space or database on the Internet, MySQL cost less, so want to turn SQL Server to MySQL ...

Note: When you install MySQL to select the text set for UTF8, otherwise you will not be able to use Chinese (you can also use UTF8 when you create the database, but I do not know how to set up the database when the EF, I hope the master pointing)

The EF package that references MySQL in the project

Install via NuGet Package Manager: EntityFramework6.1.3, mysql.data.entity6.9.8

You can also use the NuGet command line to add:

Install-package MySql.Data.Entity

Second, the new related class

1. New User entity class

and define the field length of the instance, the error of specified key was too Long;max key length be 767 bytes is not defined, because the string type directly maps to MySQL is longtext, and MySQL Supports maximum length of 767 bytes.

public class User
{public
int Id {get; set;}
[Stringlength ()]
public string UserName {get; set;}
[MaxLength (30)]

2, New Mycontext class

and explain the implementation with MySQL [Dbconfigurationtype (typeof (Mysqlefconfiguration))]

[Dbconfigurationtype (typeof (Mysqlefconfiguration))]
public class Mycontext:dbcontext
{public
mycontext ()
: Base ("Name=mycontext")// ConnectionString name
{
} public
dbset<user> Users {get; set;}
} in Web.config

3. Write test code

Database.setinitializer (New dropcreatedatabaseifmodelchanges<mycontext> ());
var context = new Mycontext ();
Inserts a row value context
. Users.add (new User {UserName = "ef6mysql"});

Third, the configuration web.config

Add the following code to <connectionStrings>:

<add name= "mycontext" connectionstring= "Data source=localhost;port=3306;initial catalog=mysql_ef;user id=root; Password=root "providername=" MySql.Data.MySqlClient "/>

The

Complete web.config is 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--> <section name= "EntityFramework" type= " System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, version=6.0.0.0, Culture=neutral,
publickeytoken=b77a5c561934e089 "requirepermission=" false "/> </configSections> <entityFramework>
<defaultconnectionfactory type= "System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/> <providers> <provider invariantname= "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.8.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.8.0, Culture=neutral,
Publickeytoken=c5687fc88969c44d "/> </DbProviderFactories> </system.data> <connectionStrings> <add name= "mycontext" connectionstring= "Data source=localhost;port=3306;initial catalog=mysql_ef;user id=root;  Password=root "providername=" MySql.Data.MySqlClient "/> </connectionStrings> </configuration>

Finally, run the program to complete the automatic creation of the database

Problems

• Error message: Specified Key was too Long;max key length is 767 bytes

1 See if the String Type property of the entity is set to a length

2 The Mycontext class is declared as a living MySQL data type [Dbconfigurationtype (typeof (Mysqlefconfiguration))]

• Error prompts: Model compatibility cannot be checked because the database does not contain Model metadata

Rerun the program after deleting the generated database

• Error message: Sequence does not contain any matching elements

Check:

For example: 1.

public class Employee
{
[Key] public
int EmployeeId {get; set;}
public string Name {get; set;}
[ForeignKey ("ManagerID")]
Public Employee Manager {get; set;}
public int ManagerID {get; set;}

2.[column (typename= "VARCHAR (254))]" public string ColumnName {get; set;}, change to: [MaxLength (254)] [Column (typename=) VARCHAR ")] public string ColumnName {get; set;} 3. (The following code has not been tested, as I am not using it, in the next article will be tested)

Modelbuilder.entity<category> ()
. Haskey (c => c.idcategory)
. Hasoptional (P => p.children)
. Withmany ()
. Hasforeignkey (c => C.childrenid);

Change into:

Modelbuilder.entity<category> ()
. Haskey (c => c.idcategory)
. Hasmany (P => p.children)
. Withoptional ()
. Hasforeignkey (c => C.childrenid);

. Withmany () replaced by. Withoptional ()

The above is a small set for you to introduce the use of MySQL in the EF method and the whole description of common problems, I hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.