1. 程式人生 > >使用EntityFramework6連線MySql資料庫(code first方式)

使用EntityFramework6連線MySql資料庫(code first方式)

demo託管地址:http://git.oschina.net/uustudy/ASP.NET-CodeFirst-MySQL-Demo.git

首先和DB First那篇文章一樣,準備工具都要一樣的。安裝包順序也是一樣的。

web.config檔案中加入這些:

<entityFramework codeConfigurationType="MySql.Data.Entity.MySqlEFConfiguration, MySql.Data.Entity.EF6">
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"
/> <providers> <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" /> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"
/> </providers> </entityFramework> <connectionStrings> <add name="MyContext" connectionString="Data Source=localhost;port=3306;Initial Catalog=MyBook;user id=root;password=123456;" providerName="MySql.Data.MySqlClient" /> </connectionStrings>

新建User類

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace CodeFirstMysql
{
    public class User
    {
        public int Id { get; set; }
        public string UserName { get; set; }
        //預設string對映到mysql裡是longtext型別的,加長度之後就變成varchar了
     [MaxLength(
30)] public string PassWord { get; set; } } }

新建MyContext類,此類繼承DbContext

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;

namespace CodeFirstMysql
{
    public class MyContext : DbContext
    {
        public MyContext()
            : base("name=MyContext")//web.config中connectionstring的名字
        {
        }

        public DbSet<User> Users { get; set; }
    }
}

Default.aspx.cs檔案內容:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CodeFirstMysql
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            InitData();
        }

        private void InitData()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());
            var context = new MyContext();
       //插入一行值 context.Users.Add(
new User {UserName = "EF6-MySQL-Code-First"}); context.SaveChanges(); } } }

執行之後看效果:

show tables:

desc table:

表中資料: