Go Nopcommerce Multi-database scenario

Source: Internet
Author: User
Tags nopcommerce

This article transferred from: http://www.cnblogs.com/YUTOUYUWEI/p/5538200.html

Sometimes a project needs to connect multiple databases to enable the sharing of data from different databases in the same project.

If NOP is already installed, you will need to create a new table in the second database, and NOP cannot automatically migrate to implement the second or more databases, so this requires us to do it manually.

1, in SQL Server to create a new database, I am here to create a new testdb, the table is testtable.

Use [Testdb]goset ansi_nulls ongoset quoted_identifier ongocreate TABLE [dbo]. [TestTable] (       [Id] [int] IDENTITY () not NULL,       [Name] [nvarchar] (255) is 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, add the entity, in Nop.core under the domain Add a folder Otherdb, in Otherdb Add a TestTable class, Inherit baseentity

TestTable:

namespace nop.core.domain.otherdb{public    class testtable:baseentity    {public        string Name {get; set;}
Public DateTime CREATEDONUTC {get; set;}} }

3. Add a map, add a Otherdb folder under Nop.data Mapping, add a Testtablemap mapping class in Otherdb, inherit 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, add a new DbContext, Add a Ohterdb in Nop.data, add a Otherdbobjectcontext class to inherit DbContext and Idbcontext, add a otherdbefstartuptask inheritance Istarttask

Otherdbobjectcontext:

Namespace nop.data.otherdb{public class Otherdbobjectcontext:dbcontext, Idbcontext {public OTHERDBOBJECTC Ontext (String nameorconnectionstring): Base (nameorconnectionstring) {} protected Overrid e void onmodelcreating (Dbmodelbuilder modelBuilder) {modelBuilder.Configurations.Add (New Testtablemap ()             ); Base.        Onmodelcreating (ModelBuilder); public string Createdatabasescript () {return (Iobjectcontextadapter).        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[] Paramet        ERS) 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. Add a new database connection string text file to connect to the TestDB database, add a text file named OtherDbSetting.txt below the App_Data below Nop.web add a connection string

Dataprovider:sqlserver

Dataconnectionstring:data Source=.;i Nitial catalog=testdb;integrated Security=false; Persist Security Info=false; User id= login status; password= Login Password

Change the database connection name

6, in Autofac inject new otherdbobjectcontext, in Nop.webframework create a new Otherdb folder, inside Add a Dependencyregistrar class

Dependencyregistrar:

Namespace nop.web.framework.otherdb{public class Dependencyregistrar:idependencyregistrar {protected Virt UAL string MapPath (string path) {if (hostingenvironment.ishosted) {return Ho            Stingenvironment.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.configur ation.            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.dataconne ctionstring)).            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;} }    }}

Add all without problems, add additional business implementation code, and rebuild the solution. This program trial Nop3.4 version and above, if there is a prior to NOP or update a version of the difference, please revise it at your discretion.

--Fish head tail qq:875755898

Go Nopcommerce Multi-database scenario

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.