nopcommerce connect two databases

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
9 years ago
version:nopcommerce3.3
I want to connect two databases in the nopcommerce。
Can this function been done?
Thanks!
9 years ago
Would you be more specific?
9 years ago
New York wrote:
Would you be more specific?

I have two websites, these two websites need to data Interactions each other.
I want nopcommerce  to access other database, how can I do?
9 years ago
What is the "other database"?  Is it another nopCommerce DB?  What data interactions do you need?
9 years ago
New York wrote:
What is the "other database"?  Is it another nopCommerce DB?  What data interactions do you need?

Thank you , New York
I have two DB. One is used by nopcommerce, another is used by another website.
nopcommerce side need to get data from another website database.
9 years ago
cqjiyong wrote:

I have two DB. One is used by nopcommerce, another is used by another website.
nopcommerce side need to get data from another website database.

Please give more specific example of the data in the other website and how you would like to use it in the Nop site and / or the reverse way
In general you could have interaction by means of web services
9 years ago
you can use 2 databases  

create the tables and their maps

create a new ObjectContext copy the Nop one and change the name
add the new tables to the OnModelCreating method


create a new EfStartUpTask to set the above

create a new txt file, place it in the app_data folder. this file should set the sql connection string
add the new ObjectContext, with the path to the file above,  to the DependencyRegistrar (including the new tables)

its working I've been using it for a while

GL
9 years ago
hezyz wrote:
you can use 2 databases  

create the tables and their maps

create a new ObjectContext copy the Nop one and change the name
add the new tables to the OnModelCreating method


create a new EfStartUpTask to set the above

create a new txt file, place it in the app_data folder. this file should set the sql connection string
add the new ObjectContext, with the path to the file above,  to the DependencyRegistrar (including the new tables)

its working I've been using it for a while

GL


Thank you,hezyz.
I get a try with what you said, but failed.
Can you give me sample code? thank you again.
9 years ago
Working in version 3.4, u need to modify to version 3.3

add new table in new database

Table



using System;

namespace Nop.Core.Domain.AnyThing
{
    /// <summary>
    /// Represents a
    /// </summary>
    public partial class yourTable : BaseEntity
    {
        /// <summary>
        /// Gets or sets the name
        /// </summary>
        public virtual string Name { get; set; }

        /// <summary>
        /// Gets or sets the date and time of instance creation
        /// </summary>
        public virtual DateTime CreatedOnUtc { get; set; }


    }
}



Map

using Nop.Core.Domain.AnyThing;

namespace Nop.Data.Mapping.AnyThing
{
    public partial class yourTableMap : NopEntityTypeConfiguration<yourTable>
    {
        public yourTableMap()
        {
            this.ToTable("TableName");

            this.HasKey(fd => fd.Id);
        }
    }
}


ObjectContext.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Reflection;
using Nop.Core;
using Nop.Data.Mapping.AnyThing;

namespace Nop.Data.AnyThing
{
    /// <summary>
    /// Object context
    /// </summary>
    public class AnyThingObjectContext : DbContext, IDbContext
    {
        #region Ctor

        public AnyThingObjectContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
            //((IObjectContextAdapter) this).ObjectContext.ContextOptions.LazyLoadingEnabled = true;
        }
        
        #endregion

        #region Utilities

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new yourTableMap());
          
            //disable EdmMetadata generation
            //modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
            base.OnModelCreating(modelBuilder);
        }

        
        #endregion

        #region Methods
        public string CreateDatabaseScript()
        {
            return ((IObjectContextAdapter)this).ObjectContext.CreateDatabaseScript();
        }

        public new IDbSet<TEntity> Set<TEntity>() where TEntity : BaseEntity
        {
            return base.Set<TEntity>();
        }

        public IList<TEntity> ExecuteStoredProcedureList<TEntity>(string commandText, params object[] parameters) where TEntity : BaseEntity, new()
        {
            throw new NotImplementedException();
        }

        public IEnumerable<TElement> SqlQuery<TElement>(string sql, params object[] parameters)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Executes the given DDL/DML command against the database.
        /// </summary>
        /// <param name="sql">The command string</param>
        /// <param name="timeout">Timeout value, in seconds. A null value indicates that the default value of the underlying provider will be used</param>
        /// <param name="parameters">The parameters to apply to the command string.</param>
        /// <returns>The result returned by the database after executing the command.</returns>
        public int ExecuteSqlCommand(string sql, bool doNotEnsureTransaction = false, int? timeout = null, params object[] parameters)
        {
            throw new NotImplementedException();
        }
    
        #endregion


    }
}


EfStartUpTask.cs


using Nop.Core;
using Nop.Core.Data;
using Nop.Core.Infrastructure;
using System.Data.Entity;

namespace Nop.Data.AnyThing
{
    public class EfStartUpTask : IStartupTask
    {
        public void Execute()
        {
            //It's required to set initializer to null (for SQL Server Compact).
            //otherwise, you'll get something like "The model backing the 'your context name' context has changed since the database was created. Consider using Code First Migrations to update the database"
            Database.SetInitializer<AnyThingObjectContext>(null);
        }

        public int Order
        {
            //ensure that this task is run first
            get { return -1000; }
        }
    }
}



DependencyRegistrar.cs


using Autofac;
using Autofac.Core;
using Autofac.Integration.Mvc;
using Nop.Core.Data;
using Nop.Core.Domain.AnyThing;
using Nop.Core.Infrastructure;
using Nop.Core.Infrastructure.DependencyManagement;
using Nop.Data;
using Nop.Data.AnyThing;
using System;
using System.IO;
using System.Web.Hosting;


namespace Nop.Web.AnyThing
{
    public class DependencyRegistrar : IDependencyRegistrar
    {
        protected virtual string MapPath(string path)
        {
            if (HostingEnvironment.IsHosted)
            {
                //hosted
                return HostingEnvironment.MapPath(path);
            }
            else
            {
                //not hosted. For example, run in unit tests
                string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\');
                return Path.Combine(baseDirectory, path);
            }
        }

        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            
            #region Data

            //data layer
            var dataSettingsManager = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings(Path.Combine(MapPath("~/App_Data/"), "AnyThing.txt"));

            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                //register named context
                builder.Register<IDbContext>(c => new AnyThingObjectContext(dataProviderSettings.DataConnectionString))
                    .Named<IDbContext>("nop_object_context_anything")
                    .InstancePerHttpRequest();

                builder.Register<AnyThingObjectContext>(c => new AnyThingObjectContext(dataProviderSettings.DataConnectionString))
                    .InstancePerHttpRequest();
            }
            else
            {
                //register named context
                builder.Register<IDbContext>(c => new AnyThingObjectContext(c.Resolve<DataSettings>().DataConnectionString))
                    .Named<IDbContext>("nop_object_context_anything")
                    .InstancePerHttpRequest();

                builder.Register<AnyThingObjectContext>(c => new AnyThingObjectContext(c.Resolve<DataSettings>().DataConnectionString))
                    .InstancePerHttpRequest();
            }

            //override required repository with our custom context
            builder.RegisterType<EfRepository<yourTable>>()
                .As<IRepository<yourTable>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_anything"))
                .InstancePerHttpRequest();
            #endregion
        }

        public int Order
        {
            get { return 1; }
        }
    }
}



place the txt file in your app_data folder
anyThing.txt
the following is for windows authentication  connection


DataProvider: sqlserver
DataConnectionString: Data Source=ServerName;Initial Catalog=DataBaseName;Integrated Security=True;Persist Security Info=False;



I u install a fresh Nop make sure to place the anyThing.txt file before u install (Nop will not create it)

If u use an installed store, u need to create the database and the tables manually

change the anyThing, yourTable to something else

should work
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.