如何在单个nopcommerce插件

时间:2016-12-19 12:59:27

标签: asp.net-mvc-5 nopcommerce

我想在nopcommerce创建一个插件,它有很多重量运输选项,我需要2个表,一个用于发货详情,另一个用于邻省,与省表有多对多的关系。
如何在一个插件中创建两个表? 所有文档都解释单个插件中的单个表 enter image description here

public partial class ShippingByWeightRecord : BaseEntity
{
    /// <summary>
    /// Gets or sets the store identifier
    /// </summary>
    public int StoreId { get; set; }

    /// <summary>
    /// Gets or sets the warehouse identifier
    /// </summary>
    public int WarehouseId { get; set; }

    /// <summary>
    /// Gets or sets the country identifier
    /// </summary>
    public int CountryId { get; set; }

    /// <summary>
    /// Gets or sets the state/province identifier
    /// </summary>
    public int StateProvinceId { get; set; }

    /// <summary>
    /// Gets or sets the zip
    /// </summary>
    public string Zip { get; set; }

    /// <summary>
    /// Gets or sets the shipping method identifier
    /// </summary>
    public int ShippingMethodId { get; set; }

    /// <summary>
    /// Gets or sets the "from" value
    /// </summary>
    public decimal From { get; set; }

    /// <summary>
    /// Gets or sets the "to" value
    /// </summary>
    public decimal To { get; set; }

    /// <summary>
    /// Gets or sets the additional fixed cost
    /// </summary>
    public decimal AdditionalFixedCost { get; set; }

    /// <summary>
    /// Gets or sets the shipping charge percentage (of subtotal)
    /// </summary>
    public decimal PercentageRateOfSubtotal { get; set; }

    /// <summary>
    /// Gets or sets the shipping charge amount (per weight unit)
    /// </summary>
    public decimal RatePerWeightUnit { get; set; }

    /// <summary>
    /// Gets or sets the lower weight limit
    /// </summary>
    public decimal LowerWeightLimit { get; set; }
}


 public partial class NeighborProvinceRecord: BaseEntity
{
    public int ProvinceId { get; set; }
    public int NProvinceId { get; set; }
}  

    public partial class ShippingByWeightRecordMap : NopEntityTypeConfiguration<ShippingByWeightRecord>
{
    public ShippingByWeightRecordMap()
    {
        this.ToTable("ShippingByWeight");
        this.HasKey(x => x.Id);

        this.Property(x => x.Zip).HasMaxLength(400);
    }
}  

public partial class NeighborProvinceMap:NopEntityTypeConfiguration     {         public NeighborProvinceMap()         {             this.ToTable( “NeighborProvince”);             this.HasKey(x =&gt; x.Id);

    }
}


public class ShippingByWeightObjectContext : DbContext, IDbContext
{
    #region Ctor

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

    #endregion

    #region Utilities

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new ShippingByWeightRecordMap());

        //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>();
    }

    /// <summary>
    /// Install
    /// </summary>
    public void Install()
    {
        //create the table
        var dbScript = CreateDatabaseScript();
        Database.ExecuteSqlCommand(dbScript);
        SaveChanges();
    }

    /// <summary>
    /// Uninstall
    /// </summary>
    public void Uninstall()
    {
        //drop the table
        var tableName = this.GetTableName<ShippingByWeightRecord>();
        //var tableName = "ShippingByWeight";
        this.DropPluginTable(tableName);
    }

    /// <summary>
    /// Execute stores procedure and load a list of entities at the end
    /// </summary>
    /// <typeparam name="TEntity">Entity type</typeparam>
    /// <param name="commandText">Command text</param>
    /// <param name="parameters">Parameters</param>
    /// <returns>Entities</returns>
    public IList<TEntity> ExecuteStoredProcedureList<TEntity>(string commandText, params object[] parameters) where TEntity : BaseEntity, new()
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// Creates a raw SQL query that will return elements of the given generic type.  The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type. The type does not have to be an entity type. The results of this query are never tracked by the context even if the type of object returned is an entity type.
    /// </summary>
    /// <typeparam name="TElement">The type of object returned by the query.</typeparam>
    /// <param name="sql">The SQL query string.</param>
    /// <param name="parameters">The parameters to apply to the SQL query string.</param>
    /// <returns>Result</returns>
    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="doNotEnsureTransaction">false - the transaction creation is not ensured; true - the transaction creation is ensured.</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();
    }

    /// <summary>
    /// Detach an entity
    /// </summary>
    /// <param name="entity">Entity</param>
    public void Detach(object entity)
    {
        if (entity == null)
            throw new ArgumentNullException("entity");

        ((IObjectContextAdapter)this).ObjectContext.Detach(entity);
    }

    #endregion

    #region Properties

    /// <summary>
    /// Gets or sets a value indicating whether proxy creation setting is enabled (used in EF)
    /// </summary>
    public virtual bool ProxyCreationEnabled
    {
        get
        {
            return this.Configuration.ProxyCreationEnabled;
        }
        set
        {
            this.Configuration.ProxyCreationEnabled = value;
        }
    }

    /// <summary>
    /// Gets or sets a value indicating whether auto detect changes setting is enabled (used in EF)
    /// </summary>
    public virtual bool AutoDetectChangesEnabled
    {
        get
        {
            return this.Configuration.AutoDetectChangesEnabled;
        }
        set
        {
            this.Configuration.AutoDetectChangesEnabled = value;
        }
    }

    #endregion
}


public class NeighborProvinceContext : DbContext, IDbContext
{
    #region Ctor

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

    #endregion

    #region Utilities

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new NeighborProvinceMap());

        //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>();
    }

    /// <summary>
    /// Install
    /// </summary>
    public void Install()
    {
        //create the table
        var dbScript = CreateDatabaseScript();
        Database.ExecuteSqlCommand(dbScript);
        SaveChanges();
    }

    /// <summary>
    /// Uninstall
    /// </summary>
    public void Uninstall()
    {
        //drop the table
        var tableName = this.GetTableName<NeighborProvinceRecord>();
        //var tableName = "ShippingByWeight";
        this.DropPluginTable(tableName);
    }

    /// <summary>
    /// Execute stores procedure and load a list of entities at the end
    /// </summary>
    /// <typeparam name="TEntity">Entity type</typeparam>
    /// <param name="commandText">Command text</param>
    /// <param name="parameters">Parameters</param>
    /// <returns>Entities</returns>
    public IList<TEntity> ExecuteStoredProcedureList<TEntity>(string commandText, params object[] parameters) where TEntity : BaseEntity, new()
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// Creates a raw SQL query that will return elements of the given generic type.  The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type. The type does not have to be an entity type. The results of this query are never tracked by the context even if the type of object returned is an entity type.
    /// </summary>
    /// <typeparam name="TElement">The type of object returned by the query.</typeparam>
    /// <param name="sql">The SQL query string.</param>
    /// <param name="parameters">The parameters to apply to the SQL query string.</param>
    /// <returns>Result</returns>
    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="doNotEnsureTransaction">false - the transaction creation is not ensured; true - the transaction creation is ensured.</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();
    }

    /// <summary>
    /// Detach an entity
    /// </summary>
    /// <param name="entity">Entity</param>
    public void Detach(object entity)
    {
        if (entity == null)
            throw new ArgumentNullException("entity");

        ((IObjectContextAdapter)this).ObjectContext.Detach(entity);
    }

    #endregion

    #region Properties

    /// <summary>
    /// Gets or sets a value indicating whether proxy creation setting is enabled (used in EF)
    /// </summary>
    public virtual bool ProxyCreationEnabled
    {
        get
        {
            return this.Configuration.ProxyCreationEnabled;
        }
        set
        {
            this.Configuration.ProxyCreationEnabled = value;
        }
    }

    /// <summary>
    /// Gets or sets a value indicating whether auto detect changes setting is enabled (used in EF)
    /// </summary>
    public virtual bool AutoDetectChangesEnabled
    {
        get
        {
            return this.Configuration.AutoDetectChangesEnabled;
        }
        set
        {
            this.Configuration.AutoDetectChangesEnabled = value;
        }
    }

    #endregion
}

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<ShippingByWeightObjectContext>(null);
        Database.SetInitializer<NeighborProvinceContext>(null);
    }

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

public class DependencyRegistrar : IDependencyRegistrar
{
    /// <summary>
    /// Register services and interfaces
    /// </summary>
    /// <param name="builder">Container builder</param>
    /// <param name="typeFinder">Type finder</param>
    /// <param name="config">Config</param>
    public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder, NopConfig config)
    {
        builder.RegisterType<ShippingByWeightService>().As<IShippingByWeightService>().InstancePerLifetimeScope();

        //data context
        this.RegisterPluginDataContext<ShippingByWeightObjectContext>(builder, "nop_object_context_shipping_weight_zip");
        this.RegisterPluginDataContext<NeighborProvinceContext>(builder, "nop_object_context_shipping_NeighborProvince");


        //override required repository with our custom context
        builder.RegisterType<EfRepository<ShippingByWeightRecord>>()
            .As<IRepository<ShippingByWeightRecord>>()
            .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_shipping_weight_zip"))
            .InstancePerLifetimeScope();
        builder.RegisterType<EfRepository<NeighborProvinceRecord>>()
            .As<IRepository<NeighborProvinceRecord>>()
            .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_shipping_NeighborProvince"))
            .InstancePerLifetimeScope();
    }

    /// <summary>
    /// Order of this dependency registrar implementation
    /// </summary>
    public int Order
    {
        get { return 1; }
    }
}

0 个答案:

没有答案