[轉]NopCommerce 多資料庫方案

來源:互聯網
上載者:User

標籤:man   struct   _id   test   settings   web   value   log   tab   

本文轉自:http://www.cnblogs.com/YUTOUYUWEI/p/5538200.html

有時候一個項目需要串連多個資料庫,以實現不同資料庫的資料在同個項目的共用。

如果已經安裝了nop,則需要在第二個資料庫建立一個表,nop現在無法自動通過遷移來實現第二個或者更多資料庫,所以這點需要我們手動去操作。

1、在SQLServer建立一個資料庫,我這裡建立的是TestDb,表為TestTable。

USE [TestDb]GOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[TestTable](       [Id] [int] IDENTITY(1,1) NOT NULL,       [Name] [nvarchar](255) NOT NULL,       [CreatedOnUtc] [datetime] NULL, CONSTRAINT [PK_TestTable] PRIMARY KEY CLUSTERED(       [Id] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GO

2、添加實體,在Nop.Core下的Domain添加一個檔案夾OtherDb,在OtherDb添加一個TestTable類,繼承BaseEntity

TestTable:

namespace Nop.Core.Domain.OtherDb{    public class TestTable : BaseEntity    {        public string Name { get; set; }
public DateTime CreatedOnUtc { get; set; } }}

3、添加映射,在Nop.Data下的Mapping添加一個OtherDb檔案夾,在OtherDb添加一個TestTableMap映射類,繼承NopEntityTypeConfiguration< TestTable >

TestTableMap:

namespace Nop.Data.Mapping.OtherDb{    public class TestTableMap : NopEntityTypeConfiguration<TestTable>    {        public TestTableMap()        {            ToTable("TestTable");
HasKey(t => t.Id);
Property(t => t.Name).IsRequired().HasMaxLength(255); } }}

4、添加新的DbContext,在Nop.Data添加一個OhterDb,裡面添加一個OtherDbObjectContext類繼承DbContext和IDbContext,添加一個OtherDbEfStartUpTask繼承IStartTask

OtherDbObjectContext:

namespace Nop.Data.OtherDb{    public class OtherDbObjectContext : DbContext, IDbContext    {        public OtherDbObjectContext(string nameOrConnectionString)            : base(nameOrConnectionString)        {        }        protected override void OnModelCreating(DbModelBuilder modelBuilder)        {            modelBuilder.Configurations.Add(new TestTableMap());             base.OnModelCreating(modelBuilder);        }        public string CreateDatabaseScript()        {            return ((IObjectContextAdapter)this).ObjectContext.CreateDatabaseScript();        }        public new IDbSet<TEntity> Set<TEntity>() where TEntity : Core.BaseEntity        {            return base.Set<TEntity>();        }        public IList<TEntity> ExecuteStoredProcedureList<TEntity>(string commandText, params object[] parameters) where TEntity : Core.BaseEntity, new()        {            throw new NotImplementedException();        }        public IEnumerable<TElement> SqlQuery<TElement>(string sql, params object[] parameters)        {            throw new NotImplementedException();        }        public int ExecuteSqlCommand(string sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters)        {            throw new NotImplementedException();        }
public void Detach(object entity) { throw new NotImplementedException(); }
public bool ProxyCreationEnabled { get { return this.Configuration.ProxyCreationEnabled; } set { this.Configuration.ProxyCreationEnabled = value; } } public bool AutoDetectChangesEnabled { get { return this.Configuration.AutoDetectChangesEnabled; } set { this.Configuration.AutoDetectChangesEnabled = value; } } }}

OtherDbEfStartUpTask:

namespace Nop.Data.OtherDb{    public class OtherDbEfStartUpTask : IStartupTask    {        public void Execute()        {            Database.SetInitializer<OtherDbObjectContext>(null);        }        public int Order        {            get { return -1000; }        }    }
}

5、添加新的資料庫連接字串文字檔,用於串連TestDb資料庫,在Nop.Web下面的App_Data下面添加一個文字檔命名OtherDbSetting.txt裡面添加連接字串

DataProvider: sqlserver

DataConnectionString: Data Source=.;Initial Catalog=TestDb;Integrated Security=False;Persist Security Info=False;User ID=登陸身份;Password=登陸密碼

改變資料庫連接名即可

 

6、在autofac注入新的OtherDbObjectContext,在Nop.WebFramework建立一個OtherDb檔案夾,裡面添加一個DependencyRegistrar類

DependencyRegistrar:

namespace Nop.Web.Framework.OtherDb{    public class DependencyRegistrar : IDependencyRegistrar    {        protected virtual string MapPath(string path)        {            if (HostingEnvironment.IsHosted)            {                return HostingEnvironment.MapPath(path);            }            else            {                string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;                path = path.Replace("~/", "").TrimStart(‘/‘).Replace(‘/‘, ‘\\‘);                return Path.Combine(baseDirectory, path);            }        }        public void Register(ContainerBuilder builder, Core.Infrastructure.ITypeFinder typeFinder, Core.Configuration.NopConfig config)        {            var dataSettingManager = new DataSettingsManager();            var dataProviderSettings = dataSettingManager.LoadSettings(Path.Combine(MapPath("~/App_Data/"), "OtherDbSetting.txt"));            if (dataProviderSettings != null && dataProviderSettings.IsValid())            {                builder.Register<IDbContext>(c => new OtherDbObjectContext(dataProviderSettings.DataConnectionString))                    .Named<IDbContext>("nop_object_context_otherdb").InstancePerLifetimeScope();                //builder.Register<OtherDbObjectContext>(                //    c => new OtherDbObjectContext(dataProviderSettings.DataConnectionString)).InstancePerLifetimeScope();            }            else            {                builder.Register<IDbContext>(                    c => new OtherDbObjectContext(c.Resolve<DataSettings>().DataConnectionString)).InstancePerLifetimeScope();                //builder.Register(                //    c => new OtherDbObjectContext(c.Resolve<DataSettings>().DataConnectionString))                //    .InstancePerLifetimeScope();            }            builder.RegisterType<EfRepository<TestTable>>()                .As<IRepository<TestTable>>()                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_otherdb"))                .InstancePerLifetimeScope();        }        public int Order        {            get { return -1; }        }    }}

 

全部添加沒問題後,添加其他業務實現代碼,重建解決方案即可。 此方案試用Nop3.4版本及以上,如有跟nop前期或者更新某個版本有差異,請自行斟酌修改。

 

-- 魚頭魚尾 QQ:875755898

 

[轉]NopCommerce 多資料庫方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.