nopcommerce mysql_nopCommerce如何支持MySQL

nopcommerce mysql_nopCommerce如何支持MySQL此方法支持 nopCommerce2 4 以上版本 缺少的代码 可参照 nopCommerce2 6 源码 在工程 Easy Data 中 1 添加 MySqlConnect 和 MySqlDataPro 在 Easy Data 目录下添加两个 Class MySqlConnect 和 MySqlDataPro MySqlConnect using

此方法支持nopCommerce2.4以上版本(缺少的代码,可参照nopCommerce2.6源码)

在工程Easy.Data中:

1、添加MySqlConnectionFactory和MySqlDataProvider

在Easy.Data目录下添加两个Class,MySqlConnectionFactory和MySqlDataProvider,

MySqlConnectionFactory:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

usingMySql.Data.MySqlClient;usingSystem;usingSystem.Collections.Generic;usingSystem.Data.Common;usingSystem.Data.Entity.Infrastructure;usingSystem.Linq;usingSystem.Text;namespaceEasy.Data

{public classMySqlConnectionFactory : IDbConnectionFactory

{private readonly string_baseConnectionString;private Func_providerFactoryCreator;publicMySqlConnectionFactory()

{

}public MySqlConnectionFactory(stringbaseConnectionString)

{this._baseConnectionString =baseConnectionString;

}public DbConnection CreateConnection(stringnameOrConnectionString)

{string connectionString =nameOrConnectionString;bool treatAsConnectionString = nameOrConnectionString.IndexOf(‘=’) >= 0;if (!treatAsConnectionString)

{

MySqlConnectionStringBuilder builder= new MySqlConnectionStringBuilder(this.BaseConnectionString);

builder.Server=nameOrConnectionString;

connectionString=builder.ConnectionString;

}

DbConnection connection= null;try{

connection= this.ProviderFactory(“MySql.Data.MySqlClient”).CreateConnection();

connection.ConnectionString=connectionString;

}catch{

connection= newMySqlConnection(connectionString);

}returnconnection;

}public stringBaseConnectionString

{get{return this._baseConnectionString;

}

}internal FuncProviderFactory

{get{

Func func1 = this._providerFactoryCreator;return delegate(stringname)

{returnDbProviderFactories.GetFactory(name);

};

}set{this._providerFactoryCreator =value;

}

}

}

}

View Code

MySqlDataProvider:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

usingEasy.Data.Initializers;usingMySql.Data.MySqlClient;usingSystem;usingSystem.Collections.Generic;usingSystem.Data.Common;usingSystem.Data.Entity;usingSystem.Data.Entity.Infrastructure;usingSystem.IO;usingSystem.Linq;usingSystem.Text;usingSystem.Web.Hosting;namespaceEasy.Data

{public classMySqlDataProvider : BaseEfDataProvider

{///

///Get connection factory///

/// Connection factory

public overrideIDbConnectionFactory GetConnectionFactory()

{return newMySqlConnectionFactory();

}///

///Set database initializer///

public override voidSetDatabaseInitializer()

{//pass some table names to ensure that we have nopCommerce 2.X installed

var tablesToValidate = new[] { “Customer”, “Discount”, “Order”, “Product”, “ShoppingCartItem”};//custom commands (stored proedures, indexes)

var customCommands = new List();//use webHelper.MapPath instead of HostingEnvironment.MapPath which is not available in unit tests

customCommands.AddRange(ParseCommands(HostingEnvironment.MapPath(“~/App_Data/MySql.Indexes.sql”), false));//use webHelper.MapPath instead of HostingEnvironment.MapPath which is not available in unit tests

customCommands.AddRange(ParseCommands(HostingEnvironment.MapPath(“~/App_Data/MySql.StoredProcedures.sql”), false));var initializer = new CreateTablesIfNotExist(tablesToValidate, customCommands.ToArray());

Database.SetInitializer(initializer);

}protected virtual string[] ParseCommands(string filePath, boolthrowExceptionIfNonExists)

{if (!File.Exists(filePath))

{if(throwExceptionIfNonExists)throw new ArgumentException(string.Format(“Specified file doesn’t exist – {0}”, filePath));else

return new string[0];

}var statements = new List();using (var stream =File.OpenRead(filePath))using (var reader = newStreamReader(stream))

{var statement = “”;while ((statement = readNextStatementFromStream(reader)) != null)

{

statements.Add(statement);

}

}returnstatements.ToArray();

}protected virtual stringreadNextStatementFromStream(StreamReader reader)

{var sb = newStringBuilder();stringlineOfText;while (true)

{

lineOfText=reader.ReadLine();if (lineOfText == null)

{if (sb.Length > 0)returnsb.ToString();else

return null;

}//MySql doesn’t support GO, so just use a commented out GO as the separator

if (lineOfText.TrimEnd().ToUpper() == “– GO”)break;

sb.Append(lineOfText+Environment.NewLine);

}returnsb.ToString();

}///

///A value indicating whether this data provider supports stored procedures///

public override boolStoredProceduredSupported

{get { return true; }

}///

///Gets a support database parameter object (used by stored procedures)///

/// Parameter

public overrideDbParameter GetParameter()

{return newMySqlParameter();

}

}

}

View Code

2、在EfDataProviderManager.LoadDataProvider中添加一条case语句:

case “mysql”:return new MySqlDataProvider();

3、在Easy.Data.Initializers.CreateTablesIfNotExist中,对InitializeDatabase函数进行修改

将以下代码

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

if(dbExists)

{bool createTables = false;if (_tablesToValidate != null && _tablesToValidate.Length > 0)

{//we have some table names to validate

var existingTableNames = new List(context.Database.SqlQuery(“SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_type = ‘BASE TABLE'”));

createTables= existingTableNames.Intersect(_tablesToValidate, StringComparer.InvariantCultureIgnoreCase).Count() == 0;

}else{//check whether tables are already created

int numberOfTables = 0;foreach (var t1 in context.Database.SqlQuery(“SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE table_type = ‘BASE TABLE'”))

numberOfTables=t1;

createTables= numberOfTables == 0;

}if(createTables)

{//create all tables

var dbCreationScript =((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript();

context.Database.ExecuteSqlCommand(dbCreationScript);//Seed(context);

context.SaveChanges();if (_customCommands != null && _customCommands.Length > 0)

{foreach (var command in_customCommands)

context.Database.ExecuteSqlCommand(command);

}

}

}

View Code

修改至

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

if(dbExists)

{string sql = string.Empty;string countSql = string.Empty;if (context.Database.Connection.GetType() == typeof(MySqlConnection))

{

sql= string.Format(“SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_type = ‘BASE TABLE’ AND table_schema = ‘{0}'”, context.Database.Connection.Database);

countSql= string.Format(“SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE table_type = ‘BASE TABLE’ AND table_schema = ‘{0}'”, context.Database.Connection.Database);

}else{

sql= @”SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_type = ‘BASE TABLE'”;

countSql= @”SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE table_type = ‘BASE TABLE'”;

}bool createTables = false;if (_tablesToValidate != null && _tablesToValidate.Length > 0)

{//we have some table names to validate

var existingTableNames = new List(context.Database.SqlQuery(sql));

createTables= existingTableNames.Intersect(_tablesToValidate, StringComparer.InvariantCultureIgnoreCase).Count() == 0;

}else{//check whether tables are already created

int numberOfTables = 0;foreach (var t1 in context.Database.SqlQuery(countSql))

numberOfTables=t1;

createTables= numberOfTables == 0;

}if(createTables)

{//create all tables

var dbCreationScript =((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript();//Need to fix some of the script for MySql

if (context.Database.Connection.GetType() == typeof(MySqlConnection))

{//MySql doesn’t support varbinary(MAX) so it generates the script with varbinary only without//a size specified, so change to longblob…could probably do this in the mapping for these properties instead

dbCreationScript = dbCreationScript.Replace(“`PictureBinary` varbinary,”, “`PictureBinary` LONGBLOB,”);

dbCreationScript= dbCreationScript.Replace(“`DownloadBinary` varbinary,”, “`DownloadBinary` LONGBLOB,”);//Order is a keyword so need to put in quotes

dbCreationScript = dbCreationScript.Replace(“REFERENCES Order (Id)”, “REFERENCES `Order` (Id)”);//Some of the constraint names are too long for MySql, so shorten them//dbCreationScript = dbCreationScript.Replace(“ProductReview_TypeConstraint_From_CustomerContent_To_ProductReview”, “ProductReview_CustomerContent_ProductReview”);//dbCreationScript = dbCreationScript.Replace(“PollVotingRecord_TypeConstraint_From_CustomerContent_To_PollVotingRecord”, “PollVotingRecord_CustomerContent_PollVotingRecord”);//dbCreationScript = dbCreationScript.Replace(“ProductReviewHelpfulness_TypeConstraint_From_CustomerContent_To_ProductReviewHelpfulness”, “ProductReviewHelpfulnes_CustomerContent_ProductReviewHelpfulnes”);

}

context.Database.ExecuteSqlCommand(dbCreationScript);//Seed(context);

context.SaveChanges();if (_customCommands != null && _customCommands.Length > 0)

{foreach (var command in_customCommands)

context.Database.ExecuteSqlCommand(command);

}

}

}

View Code

4、在领域Model中,一些属性Mapping需要更改,因为MySQL将字符串创建成Text/MediumText/LongText,而这些格式不支持索引,所以需要将这些Mapping修改成varchar,如将

this.Property(u => u.Username).HasMaxLength(1000);this.Property(u => u.Email).HasMaxLength(1000);

修改成

this.Property(u => u.Username).HasMaxLength(1000).HasColumnType(“varchar”);this.Property(u => u.Email).HasMaxLength(1000).HasColumnType(“varchar”);

5、最后,在Easy.Web.Models.Install.InstallModel中添加MySQL相关属性

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

//MySql properties

public string MySqlConnectionInfo { get; set; }

[AllowHtml]public string MySqlServerName { get; set; }

[AllowHtml]public string MySqlDatabaseName { get; set; }

[AllowHtml]public string MySqlUsername { get; set; }

[AllowHtml]public string MySqlPassword { get; set; }public bool MySqlServerCreateDatabase { get; set; }

[AllowHtml]public string MySqlDatabaseConnectionString { get; set; }

View Code

然后,在Easy.Web.Controllers.InstallController中添加MySQL相关的函数

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

private bool mySqlDatabaseExists(stringconnectionString)

{try{//just try to connect

using (var conn = newMySqlConnection(connectionString))

{

conn.Open();

}return true;

}catch{return false;

}

}private string createMySqlDatabase(stringconnectionString)

{try{//parse database name

var builder = newMySqlConnectionStringBuilder(connectionString);var databaseName =builder.Database;//now create connection string to ‘master’ dabatase. It always exists.

builder.Database = string.Empty; //= “master”;

var masterCatalogConnectionString =builder.ToString();string query = string.Format(“CREATE DATABASE {0} COLLATE utf8_unicode_ci”, databaseName);using (var conn = newMySqlConnection(masterCatalogConnectionString))

{

conn.Open();using (var command = newMySqlCommand(query, conn))

{

command.ExecuteNonQuery();

}

}return string.Empty;

}catch(Exception ex)

{return string.Format(“An error occured when creating database: {0}”, ex.Message);

}

}private string createMySqlConnectionString(string serverName, string databaseName, string userName, string password, UInt32 timeout = 0)

{var builder = newMySqlConnectionStringBuilder();

builder.Server=serverName;

builder.Database=databaseName.ToLower();

builder.UserID=userName;

builder.Password=password;

builder.PersistSecurityInfo= false;

builder.AllowUserVariables= true;

builder.DefaultCommandTimeout= 30000;

builder.ConnectionTimeout=timeout;returnbuilder.ConnectionString;

}

View Code

最后,在Easy.Web.Views.Install.Index.cshtml中,添加MySQL的用户交互界面即可。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/208926.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月19日 上午10:27
下一篇 2026年3月19日 上午10:27


相关推荐

  • 虚函数详解[通俗易懂]

    虚函数详解[通俗易懂]文章目录一、虚函数实例二、虚函数的实现(内存布局)1、无继承情况2、单继承情况(无虚函数覆盖)3、单继承情况(有虚函数覆盖)4、多重继承情况(无虚函数覆盖)5、多重继承情况(有虚函数覆盖)三、虚函数的相关问题1、构造函数为什么不能定义为虚函数2、析构函数为什么要定义为虚函数?3、如何去验证虚函数表的存在  面向对象的语言有三大特性:继承、封装、多态。虚函数作为多态的实现方式,重要性毋庸置疑。 …

    2022年7月26日
    13
  • 网页实现中英文切换方式对比与实现

    网页实现中英文切换方式对比与实现一 使用谷歌 微软的翻译 API 优点 只须调用接口 即可轻松完成整站翻译 翻译准确度还好 缺点 谷歌被墙了 使用意义不大 微软的收费 参考 http code google com apis language translate overview html 注 网上很多的使用微软 API 的方法 现在已经无法实现 二 借助 i18n 插件 自己编写中英文对照表 用 js 控制

    2026年3月17日
    2
  • SSD目标检测分析

    SSD目标检测分析参考原文链接前言目标检测主流算法主要分为两个类型 1 two stage 方法 如 R CNN 系列 主要思路是先通过启发式方法 selectivesea 或者 CNN 网络 RPN 产生一系列稀疏的候选框 然后对这些候选框进行分类与回归 two stage 方法的优势是准确度高 2 one stage 方法 如 Yolo 和 SSD 主要思路是均匀地在图片的不同位置进行密集抽样 抽样时可以采用

    2026年3月17日
    2
  • 数据持久化

    数据持久化

    2021年7月19日
    60
  • 百度地图API显示多个标注点并添加百度样式检索窗口

    百度地图API显示多个标注点并添加百度样式检索窗口

    2021年10月10日
    49
  • mysql 拼接字符_mysql将字符串和数字拼接

    mysql 拼接字符_mysql将字符串和数字拼接数据准备CREATETABLE`user`(`id`int(11)NOTNULLAUTO_INCREMENT,`account`varchar(100)DEFAULTNULL,`password`varchar(100)DEFAULTNULL,`type`tinyint(4)DEFAULTNULL,PRIMARYKEY(`id`),UNIQUEKEY`acc…

    2022年9月30日
    5

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号