1
votes

Ok so im getting an error message about an invalid Id Column:

System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Invalid column name 'Id'. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext1 c) at System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func3 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed) at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary2 identifierValues, List1 generatedValues) at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() --- End of inner exception stack trace --- at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update() at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.b__2(UpdateTranslator ut) at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func2 updateFunction) at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update() at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35() at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction) at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.b__27() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation) at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction) at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options) at System.Data.Entity.Internal.InternalContext.SaveChanges() --- End of inner exception stack trace --- at System.Data.Entity.Internal.InternalContext.SaveChanges() at System.Data.Entity.Internal.LazyInternalContext.SaveChanges() at System.Data.Entity.DbContext.SaveChanges() at Nop.Data.EfRepository1.Insert(T entity) in C:\projects\snowys-website\Libraries\Nop.Data\EfRepository.cs:line 81 at Nop.Plugin.Widgets.Enhancements.Services.AmazonProductService.InsertAmazonProduct(AmazonProduct amazonProduct) at Nop.Plugin.Widgets.Enhancements.Events.ProductSaveConsumer.HandleEvent(EntityFinalised1 eventMessage) at Nop.Services.Events.EventPublisher.PublishToConsumer[T](IConsumer1 x, T eventMessage) in C:\projects\snowys-website\Libraries\Nop.Services\Events\EventPublisher.cs:line 40

This is my product save event class

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Nop.Core;
using Nop.Core.Domain.Catalog;
using Nop.Core.Events;
using Nop.Core.Infrastructure;
using Nop.Plugin.Widgets.Enhancements.Domain;
using Nop.Plugin.Widgets.Enhancements.Services;
using Nop.Services.Events;
using Nop.Web.Framework.Events;

namespace Nop.Plugin.Widgets.Enhancements.Events
{
/// <summary>
/// This class is used to detect when a Product has been edited so we can update the relevant Amazon fields.
/// </summary>
public class ProductSaveConsumer : IConsumer<EntityFinalised<Product>>
{
    public void HandleEvent(EntityFinalised<Product> eventMessage)
    {
        // This event is triggered multiple times when a product is updated.
        // We only want to update the amazon fields once, as to avoid
        // performance issues.
        var httpContext = HttpContext.Current;
        if (httpContext != null && httpContext.Request.Form.HasKeys() &&
            httpContext.Request.Form.Get("AmazonProductSKU") != null)
        {
            #region Fields

            // Register services we will need to update the database fields
            var _amazonProductService = EngineContext.Current.Resolve<IAmazonProductService>();

            // Other variables
            var form = httpContext.Request.Form;
            var isNewAmazonProduct = true;

            #endregion

            System.Diagnostics.Debug.WriteLine("form has been submitted");

            // Get the AmazonProduct row from our custom table for the product (if it already exists)
            // isNewAmazonProduct = false;
            var amazonProductExists = false;//_amazonProductService.GetAmazonProductById(eventMessage.Entity.Id).Exists(x => x.ProductId == eventMessage.Entity.Id);

            if (amazonProductExists) {
                isNewAmazonProduct = false;
                System.Diagnostics.Debug.WriteLine("not new amazon product");
            }
            else
            {
                isNewAmazonProduct = true;
                System.Diagnostics.Debug.WriteLine("is new amazon product");
            }

            var amazonProduct = new AmazonProduct();

            //set the product id
            amazonProduct.ProductID = Int32.Parse(eventMessage.Entity.Id.ToString());

            // Now let's update the fields
            // AmazonProductSKU
            if (!String.IsNullOrEmpty(form["AmazonProductSKU"]))
            {
                amazonProduct.AmazonProductSKU = form["AmazonProductSKU"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product sku");
            }

            // AmazonID
            if (!String.IsNullOrEmpty(form["AmazonID"]))
            {
                amazonProduct.AmazonID = form["AmazonID"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon id");
            }

            // AmazonProductIDType
            if (!String.IsNullOrEmpty(form["AmazonProductIDType"]))
            {
                amazonProduct.AmazonID = form["AmazonProductIDType"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product id type");
            }

            // AmazonProductTitle
            if (!String.IsNullOrEmpty(form["AmazonProductTitle"]))
            {
                amazonProduct.AmazonProductTitle = form["AmazonProductTitle"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product title");
            }

            // AmazonProductDescription
            if (!String.IsNullOrEmpty(form["AmazonProductDescription"]))
            {
                amazonProduct.AmazonProductDescription = form["AmazonProductDescription"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product description");
            }

            // AmazonProductManufacturer
            if (!String.IsNullOrEmpty(form["AmazonProductManufacturer"]))
            {
                amazonProduct.AmazonProductManufacturer = form["AmazonProductManufacturer"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product manufacturer");
            }

            // AmazonProductType
            if (!String.IsNullOrEmpty(form["AmazonProductType"]))
            {
                amazonProduct.AmazonProductType = form["AmazonProductType"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product type");
            }

            // AmazonProductBrandName
            if (!String.IsNullOrEmpty(form["AmazonProductBrandName"]))
            {
                amazonProduct.AmazonProductBrandName = form["AmazonProductBrandName"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product brand name");
            }

            // AmazonProductShippingTemplate
            if (!String.IsNullOrEmpty(form["AmazonProductShippingTemplate"]))
            {
                amazonProduct.AmazonProductShippingTemplate = form["AmazonProductShippingTemplate"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product shipping template");
            }

            // AmazonProductSeoRecommendedBrowserNodes1
            if (!String.IsNullOrEmpty(form["AmazonProductSeoRecommendedBrowserNodes1"]))
            {
                amazonProduct.AmazonProductSeoRecommendedBrowserNodes1 = form["AmazonProductSeoRecommendedBrowserNodes1"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product seo node 1");
            }

            // AmazonProductSeoRecommendedBrowserNodes2
            if (!String.IsNullOrEmpty(form["AmazonProductSeoRecommendedBrowserNodes2"]))
            {
                amazonProduct.AmazonProductSeoRecommendedBrowserNodes2 = form["AmazonProductSeoRecommendedBrowserNodes2"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product seo node 2");
            }

            // AmazonProductMainImgUrl
            if (!String.IsNullOrEmpty(form["AmazonProductMainImgUrl"]))
            {
                amazonProduct.AmazonProductMainImgUrl = form["AmazonProductMainImgUrl"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product main image url");
            }

            // AmazonProductCountryOfPublication
            if (!String.IsNullOrEmpty(form["AmazonProductCountryOfPublication"]))
            {
                amazonProduct.AmazonProductCountryOfPublication = form["AmazonProductCountryOfPublication"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product country of pub");
            }

            // AmazonProductMfgWarrantySwitchedOffAu
            if (!String.IsNullOrEmpty(form["AmazonProductMfgWarrantySwitchedOffAu"]))
            {
                amazonProduct.AmazonProductMfgWarrantySwitchedOffAu = form["AmazonProductMfgWarrantySwitchedOffAu"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product mfg warranty");
            }

            // AmazonKeyProductFeatures1
            if (!String.IsNullOrEmpty(form["AmazonKeyProductFeatures1"]))
            {
                amazonProduct.AmazonKeyProductFeatures1 = form["AmazonKeyProductFeatures1"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product feature 1");
            }

            // AmazonKeyProductFeatures2
            if (!String.IsNullOrEmpty(form["AmazonKeyProductFeatures2"]))
            {
                amazonProduct.AmazonKeyProductFeatures2 = form["AmazonKeyProductFeatures2"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product feature 2");
            }

            // AmazonKeyProductFeatures3
            if (!String.IsNullOrEmpty(form["AmazonKeyProductFeatures3"]))
            {
                amazonProduct.AmazonKeyProductFeatures3 = form["AmazonKeyProductFeatures3"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product feature 3");
            }

            // AmazonKeyProductFeatures4
            if (!String.IsNullOrEmpty(form["AmazonKeyProductFeatures4"]))
            {
                amazonProduct.AmazonKeyProductFeatures4 = form["AmazonKeyProductFeatures4"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product feature 4");
            }

            // AmazonKeyProductFeatures5
            if (!String.IsNullOrEmpty(form["AmazonKeyProductFeatures5"]))
            {
                amazonProduct.AmazonKeyProductFeatures5 = form["AmazonKeyProductFeatures5"].ToString();
                System.Diagnostics.Debug.WriteLine("amazon product feature 5");
            }

            // AmazonProductPrice
            if (!String.IsNullOrEmpty(form["AmazonProductPrice"].ToString()))
            {
                amazonProduct.AmazonProductPrice = Decimal.Parse(form["AmazonProductPrice"]);
                System.Diagnostics.Debug.WriteLine("amazon product price");
            }

            // Call the update or insert function (depending on whether or not the AmazonProduct already existed)
            if (isNewAmazonProduct)
            {
                _amazonProductService.InsertAmazonProduct(amazonProduct);
                System.Diagnostics.Debug.WriteLine("amazon product inserted");
            }
            else {
                _amazonProductService.UpdateAmazonProduct(amazonProduct);
                System.Diagnostics.Debug.WriteLine("amazon product updated");
            }
        }
    }
}
}

Anyone know why the error is caused, am I not accessing the product Id right?

Cheers

1
Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a minimal reproducible example.Enigmativity
I have added answer, problem was not from what I thoughtWeb Dev Guy

1 Answers

0
votes

Ok so it turns out it was a problem with how my amazonproduct.cs domain and amazonproductmap.cs were setup. Not the way I was accessing the product id.

In my amazonproduct.cs file I was inheriting the baseentity:

using Nop.Core;
using System.ComponentModel.DataAnnotations.Schema;

namespace Nop.Plugin.Widgets.Enhancements.Domain
{
    public class AmazonProduct : BaseEntity //I was inheriting the baseentity
    {
        //code omitted
    }
}

So because I was inheriting the base entity, it was using a field Id which was causing the problem.

So in my amazonproductmap I had to ignore this column:

using System.Data.Entity.ModelConfiguration;
using Nop.Plugin.Widgets.Enhancements.Domain;

namespace Nop.Plugin.Widgets.Enhancements.Data
{
public class AmazonProductMap : EntityTypeConfiguration<AmazonProduct>
{
    public AmazonProductMap()
    {
        ToTable("amazonProductInfo");
        HasKey(p => p.AmazonProductID);

        Ignore(p => p.Id); //I had to ignore this column
        //other fields omitted
    }
}
}

I hope this helps someone else :)