nopCommerce-4.10 - Fetch data from SQL via SQL query and Stored Procedure via plugin is not working

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
5 years ago
Hello,

I'm trying to fetch records from database via SQL query and stored procedure, but in both case getting same error.

Cannot create a DbSet for 'CLASSMODEL' because this type is not included in the model for the context.


Here is my code.
I checked with existing nopCommerce plugin (Nop.Plugin.Shipping.FixedByWeightByTotal) and there getting same error message.

Here is my changes in Nop.Plugin.Shipping.FixedByWeightByTotal plugin.

Created new model under Model folder: ShippingRecordModel.cs

using Nop.Core;

namespace Nop.Plugin.Shipping.FixedByWeightByTotal.Model
{
    /// <summary>
    /// Represents a shipping by weight record
    /// </summary>
    public partial class ShippingRecordModel :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; }                
    }
}





Modify ShippingByWeightByTotalObjectContext.cs file - update below methods

/// <summary>
        /// Creates a LINQ query for the query type based on a raw SQL query
        /// </summary>
        /// <typeparam name="TQuery">Query type</typeparam>
        /// <param name="sql">The raw SQL query</param>
        /// <returns>An IQueryable representing the raw SQL query</returns>
        public virtual IQueryable<TQuery> QueryFromSql<TQuery>(string sql) where TQuery : class
        {
            return this.Query<TQuery>().FromSql(sql);
        }

        /// <summary>
        /// Creates a LINQ query for the entity based on a raw SQL query
        /// </summary>
        /// <typeparam name="TEntity">Entity type</typeparam>
        /// <param name="sql">The raw SQL query</param>
        /// <param name="parameters">The values to be assigned to parameters</param>
        /// <returns>An IQueryable representing the raw SQL query</returns>
        public virtual IQueryable<TEntity> EntityFromSql<TEntity>(string sql, params object[] parameters) where TEntity : BaseEntity
        {
            return this.Set<TEntity>().FromSql(CreateSqlWithParameters(sql, parameters), parameters);
        }

        /// <summary>
        /// Modify the input SQL query by adding passed parameters
        /// </summary>
        /// <param name="sql">The raw SQL query</param>
        /// <param name="parameters">The values to be assigned to parameters</param>
        /// <returns>Modified raw SQL query</returns>
        protected virtual string CreateSqlWithParameters(string sql, params object[] parameters)
        {
            //add parameters to sql
            for (var i = 0; i <= (parameters?.Length ?? 0) - 1; i++)
            {
                if (!(parameters is DbParameter parameter))
                    continue;

                sql = $"{sql}{(i > 0 ? "," : string.Empty)} @{parameter.ParameterName}";

                //whether parameter is output
                if (parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Output)
                    sql = $"{sql} output";
            }

            return sql;
        }


Add this section in DependencyRegistrar.cs file

  //override required repository with our custom context
            builder.RegisterType<ShippingRecordModel>().As<ShippingRecordModel>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_shipping_weight_total_zip"))
                .InstancePerLifetimeScope();




Added new service in IShippingByWeightByTotalService.cs

  
IList<ShippingRecordModel> GetAllBySQL();


Implement this in ShippingByWeightByTotalService.cs



[i]In Field region

  
     private readonly ShippingByWeightByTotalObjectContext _dbContext = EngineContext.Current.Resolve<ShippingByWeightByTotalObjectContext>();


In Mothod region

     public virtual IList<ShippingRecordModel> GetAllBySQL()
        {
            var aa = _dbContext.QueryFromSql<ShippingRecordModel>("SELECT StoreId,WarehouseId,CountryId  FROM ShippingMethod").ToList();

            return aa;
        }


In controller - FixedByWeightByTotalController.cs file - > Configure() method
add below line:
 var allData = _shippingByWeightService.GetAllBySQL();


While code execute on this line, it's throw an exception.
5 years ago
For get changed plugins source code, click here

This will in identify issue.
5 years ago
rajupaladiya wrote:
For get changed plugins source code, click here

This will in identify issue.


I'm not sure ...but it might be related to Identity issue.

You need to select Id column  in SELECT query.

I'm not sure but you need to try this once.
5 years ago
With Id it also not working.
Error is not related id column name.
5 years ago
Hello,

After lot's of check, I find solution and fixed this one and it's working fine now my end.

Here is What I've change:

In ShippingByWeightByTotalObjectContext.cs file, added this line
modelBuilder.Query<ShippingRecordModel>();


So after change, OnModelCreating method is
   protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration(new ShippingByWeightByTotalRecordMap());
          
            // For Execute SQL Query
            modelBuilder.Query<ShippingRecordModel>();
            base.OnModelCreating(modelBuilder);
        }



Removed below change from DependencyRegistrar.cs
THIS IS REMOVED

 //override required repository with our custom context
            builder.RegisterType<ShippingRecordModel>().As<ShippingRecordModel>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_shipping_weight_total_zip"))
                .InstancePerLifetimeScope();



Update service and change in GetAllBySQL() method

Old Code
_dbContext.QueryFromSql<ShippingRecordModel>("SELECT StoreId,WarehouseId,CountryId  FROM ShippingByWeightByTotalRecord").ToList();


Updated Code
_dbContext.Query<ShippingRecordModel>().FromSql("SELECT StoreId, WarehouseId, CountryId FROM ShippingByWeightByTotalRecord").ToList();



For Stored Procedure same thing.
_dbContext.Query<CLASSNAME>().FromSql("SPNAME",
                   parameter1, parameter2, ...);

Thank You
5 years ago
Hello,

After lot's of check, I find solution and fixed this one and it's working fine now my end.

Here is What I've change:

In ShippingByWeightByTotalObjectContext.cs file, added this line
modelBuilder.Query<ShippingRecordModel>();


So after change, OnModelCreating method is
   protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration(new ShippingByWeightByTotalRecordMap());
          
            // For Execute SQL Query
            modelBuilder.Query<ShippingRecordModel>();
            base.OnModelCreating(modelBuilder);
        }



Removed below change from DependencyRegistrar.cs
THIS IS REMOVED

 //override required repository with our custom context
            builder.RegisterType<ShippingRecordModel>().As<ShippingRecordModel>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>("nop_object_context_shipping_weight_total_zip"))
                .InstancePerLifetimeScope();



Update service and change in GetAllBySQL() method

Old Code
_dbContext.QueryFromSql<ShippingRecordModel>("SELECT StoreId,WarehouseId,CountryId  FROM ShippingByWeightByTotalRecord").ToList();


Updated Code
_dbContext.Query<ShippingRecordModel>().FromSql("SELECT StoreId, WarehouseId, CountryId FROM ShippingByWeightByTotalRecord").ToList();



For Stored Procedure same thing.
_dbContext.Query<CLASSNAME>().FromSql("SPNAME",
                   parameter1, parameter2, ...);


Thank You
5 years ago
Hello Raju,

Thanks for sharing with us.

This code is indeed helpful for nopcommerce developer which people stuck with this issue.
5 years ago
Thank You SK.

Just need to check with default functionality, why it not work with Asp.NET Core 2.1.

In many post, I ready they downgrade to 1.X version and it's working with it, but not working with 2.1 version.
2 years ago
This post has a working solution for version 4.2 if anyone is looking for it.

https://stackoverflow.com/questions/61967882/nopcommerce-4-2-how-to-execute-stored-procedure-and-get-return-model
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.