第一步:從NuGET安裝以下套件。
- MySql.Web
- MySql.Data
- MySql.Data.Entity
- EntityFramework
- EntityFramework.zh-Hant
第二步:建立DbContent類別,並建立連線字串。
namespace My.Models
{
using System;
using System.Data.Common;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Configuration;
using System.Linq;
using MySql.Data;
using MySql.Data.Entity;
using MySql.Data.MySqlClient;
using MySql.Data.Types;
public class MysqlDB : DbContext
{
public MysqlDB(DbConnection conn, bool chkconn) : base(conn, chkconn)
{
}
public static MysqlDB CreateDBContext(string HostName, string DBName)
{
string connectionString = string.Format("Server={0};Database={1};UID=Account;Password=Pwd", HostName, DBName);
DbProviderFactory dbfactory = DbProviderFactories.GetFactory("MySql.Data.MySqlClient");
DbConnection dbConnection = dbfactory.CreateConnection();
dbConnection.ConnectionString = connectionString;
MysqlDB db = new MysqlDB(dbConnection, true);
db.Configuration.LazyLoadingEnabled = false;
dbfactory = null;
dbConnection = null;
return db;
}
}
}
沒有留言:
張貼留言