Entity Framework with Mysql code first

Source: Internet
Author: User
Tags mysql code connectionstrings

The Entity Framework 4.0 can now support the MySQL database as well, and this article will show you how to do it in code first.

1. First create a new project, add the following references in the project with NuGet:

  

2. Add the following configuration to the Web. config file:

1 < connectionStrings > 2     <  name= "Mytestcontext"  connectionString= "Data source=127.0.0.1;port= 3306;initial catalog=test;user id=root;password=; " ProviderName = "MySql.Data.MySqlClient" /> 3 </ connectionStrings >

3. New Entity class:

 Public classUser { Public intId {Get;Set; } [MaxLength ( -)]         Public stringUserName {Get;Set; } [MaxLength ( -)]         Public stringPassword {Get;Set; } [MaxLength ( -)]         Public stringEmail {Get;Set; } }

4. Create the data context for EF, and note that this class inherits DbContext

 Public class Efmysqlcontext:dbcontext    {        public  efmysqlcontext ()            base("name=mytestcontext ") // The name here is the database connection string in Web. config
{ }
     Public Get Set ; }
}

Once you have done this, you can call it in the foreground, and if the database test,ef does not exist, the database will be created. The foreground call method is as follows:

var New Efmysqlcontext ();             Context. Users.add (new"Wilbur", password="123456 "  });            Context. SaveChanges ();

After the program runs, the database is automatically generated:

The DbContext in the Entity framework generates a __migrationhistory table for use with Code frist programming mode.

Well, a simple MySQL EF code first is implemented!

Entity Framework with Mysql code first

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.