I can't migrate data to a table

2 meses atrás
I'm doing a shopping cart project, and I've created two tables one called ProductInfoDomain and the other CustomerHasCart, I can migrate the product information to the ProductInfoDomain table but I want each cart to be unique per customer so I need to relate these tables but I can't, I need help

My service

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LinqToDB;
using Nop.Core;
using Nop.Data;
using Nop.Plugin.Widgets.Samurai.Domain;

namespace Nop.Plugin.Widgets.Samurai.Services
{
    public interface ISamuraiDataService
    {
        Task ArmazenarDadosAsync(string productname, float productprice, int productid, Guid cartId);
        
        Task <List<ProductInfoDomain>> GetProdutos();


        void ExcluirProdutos(string productname);
    
        int ContadorProduto();

        void AtualizarQuantidadesBanco(string productName, int productQuantity);
    }

    public class SamuraiDataService : ISamuraiDataService
    {
        private readonly IRepository<ProductInfoDomain> _repository;
        private readonly IWorkContext _workContext;
        private readonly IRepository<CustomerHasCartDomain> _repositorycustomer;
      



        public SamuraiDataService(IRepository<ProductInfoDomain> repository, IWorkContext workContext, IRepository<CustomerHasCartDomain> repositorycustomer)
        {
            _repository = repository;
            _workContext = workContext;
            _repositorycustomer = repositorycustomer;

          
        }


        public async Task ArmazenarDadosAsync(string productname, float productprice, int productid, Guid cartId)
        {
            try
            {
                var customerid = (await _workContext.GetCurrentCustomerAsync()).Id; // Obtém o ID do cliente atual


                // Verifica se o produto já existe para este cliente e carrinho
                var existingProduct = _repository.Table.FirstOrDefault(p => p.ProductName == productname &&
                                                                            p.ProductPrice == productprice &&
                                                                            p.ProductId == productid &&
                                                                            p.CustomerId == customerid &&
                                                                            p.CartId == cartId);

                if (existingProduct != null)
                {
                    // Se o produto já existe, atualize a quantidade
                    existingProduct.ProductQuantity++;
                    await _repository.UpdateAsync(existingProduct);
                }
                else
                {
                    // Se o produto não existe, insira um novo registro
                    var newRegister = new ProductInfoDomain
                    {
                        ProductName = productname,
                        ProductPrice = productprice,
                        ProductId = productid,
                        ProductQuantity = 1,
                        CustomerId = customerid,
                        CartId = cartId
                    };
                    await _repository.InsertAsync(newRegister);
                }

                var customerCart = _repositorycustomer.Table.FirstOrDefault(cc => cc.CustomerId == customerid);

                if (customerCart == null)
                {
                    // Se não houver uma entrada correspondente, associe o carrinho ao cliente
                    customerCart = new CustomerHasCartDomain { CustomerId = customerid, CartId = cartId };
                    await _repositorycustomer.InsertAsync(customerCart);
                }
                else if (customerCart.CartId != cartId)
                {
                    // Se o carrinho associado ao cliente for diferente do carrinho atual, atualize o carrinho
                    customerCart.CartId = cartId;
                    await _repositorycustomer.UpdateAsync(customerCart);
                }



            }
            catch (Exception ex)
            {
                // Lidar com a exceção e retornar uma resposta adequada
                Console.WriteLine($"Erro ao armazenar dados: {ex.Message}");
                throw; // Rejogue a exceção para sinalizar um problema ao chamador.
            }
        }




        public async Task <List<ProductInfoDomain>> GetProdutos()
        {
            var getlist =  await _repository.Table.ToListAsync();

            if (getlist != null)
            {
                return getlist;
            }
            else
            {
                 return new List<ProductInfoDomain>();
            }

        }

        public void ExcluirProdutos(string productname)
        {
            var productToDelete = _repository.Table.FirstOrDefault(p => p.ProductName == productname);
            if (productToDelete != null)
            {
                _repository.DeleteAsync(productToDelete);
            }
        }

        public int ContadorProduto()
        {
            return _repository.Table.Sum(p => p.ProductQuantity);
        }


        public void AtualizarQuantidadesBanco(string productName, int productQuantity)
        {
            try
            {
                var product = _repository.Table.FirstOrDefault(p => p.ProductName == productName);
                if (product != null)
                {
                    product.ProductQuantity = productQuantity;
                  
                    _repository.Update(product);
                
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Erro ao atualizar quantidades no banco: " + ex.Message);
                throw; // Rejogue a exceção para sinalizar um problema ao chamador.
            }

        }


    }
}


My controller


using System;
using System.Linq;
using System.Reflection.Metadata;
using System.Threading.Tasks;
using DocumentFormat.OpenXml;
using LinqToDB;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Nop.Core;
using Nop.Plugin.Widgets.Samurai.Domain;
using Nop.Plugin.Widgets.Samurai.Services;
using Nop.Services.Security;
using Nop.Web.Framework;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Mvc.Filters;

namespace Nop.Plugin.Widgets.Samurai.Controller
{
    [Authorize]
    public class SamuraiDataBaseMigrationController : BasePluginController
    {
        private readonly ISamuraiDataService _service;
        

        public SamuraiDataBaseMigrationController(ISamuraiDataService service)
        {
            _service = service;
          
        }  

        [HttpPost]
        public async Task <ActionResult> AdicionarAoMigrateAsync([FromBody] ProductInfoDomain data)
        {

            //I receive the data from the AJAX request and check that the data has already been inserted into the table

            try
            {
                // Verifica se o produto já existe
                var produtos = await _service.GetProdutos();
                var produtoExistente = produtos.FirstOrDefault(p => p.ProductName == data.ProductName && p.ProductPrice == data.ProductPrice);
                                                            

                // Adiciona ou atualiza o produto no serviço
                await _service.ArmazenarDadosAsync(data.ProductName, data.ProductPrice, data.ProductId, data.CartId);

                if (produtoExistente != null)
                {
                    return Json(new { message = "Quantidade do produto atualizada com sucesso!" });
                }
                else
                {
                    return Json(new { message = "Informações do produto migradas com sucesso!" });
                }
            }
            catch(Exception ex)
            {

                Console.WriteLine($"Erro ao processar a solicitação: {ex.Message}");
              
                // Trate qualquer exceção que possa ocorrer durante o processo
                Response.StatusCode = 500;
                return Json(new { error = true, message = "Erro ao processar a solicitação.", ex.StackTrace });


            }

        }


    }

}



My builder CustomerHasCartDomain

using FluentMigrator.Builders.Create.Table;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Orders;
using Nop.Data.Extensions;
using System.Threading.Tasks;
using Nop.Core.Domain.Customers;
using Nop.Data.Mapping.Builders;
using Nop.Plugin.Widgets.Samurai.Domain;



namespace Nop.Plugin.Widgets.Samurai.Data
{
    public  class CustomerHasCartBuilder : NopEntityBuilder<CustomerHasCartDomain>
    {
        public override void MapEntity(CreateTableExpressionBuilder table)
        {
            table.WithColumn(nameof(CustomerHasCartDomain.Id)).AsInt32().PrimaryKey().Identity()
                 .WithColumn(nameof(CustomerHasCartDomain.CustomerId)).AsInt32()
                 .WithColumn(nameof(CustomerHasCartDomain.CartId)).AsGuid()
                 .WithColumn(nameof(CustomerHasCartDomain.ProductId)).AsInt32()
                 .WithColumn(nameof(CustomerHasCartDomain.ProductQuantity)).AsInt32();
                

        }

    }
}


My builder ProductInfoDomain

using FluentMigrator.Builders.Create.Table;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Orders;
using Nop.Data.Extensions;
using System.Threading.Tasks;
using Nop.Core.Domain.Customers;
using Nop.Data.Mapping.Builders;
using Nop.Plugin.Widgets.Samurai.Domain;

namespace Nop.Plugin.Widgets.Samurai.Data
{
    public class ProductInfoBuilder : NopEntityBuilder<ProductInfoDomain>
    {
        public override void MapEntity(CreateTableExpressionBuilder table)
        {
            table.WithColumn(nameof(ProductInfoDomain.ProductId)).AsInt32()
                 .WithColumn(nameof(ProductInfoDomain.ProductQuantity)).AsInt32()
                 .WithColumn(nameof(ProductInfoDomain.CustomerId)).AsInt32()
                 .WithColumn(nameof(ProductInfoDomain.ProductPrice)).AsDecimal(10, 2)
                 .WithColumn(nameof(ProductInfoDomain.CartId)).AsGuid().ForeignKey<CustomerHasCartDomain>()
                 .WithColumn(nameof(ProductInfoDomain.ProductName)).AsString(256);
                
        }
    }
}





2 meses atrás
I don't understand you model
ProductInfoDomain as Id column which is PK.  Yet, you are setting up FK with PoductInfoDomain.CartId
.WithColumn(nameof(ProductInfoDomain.CartId)).AsGuid().ForeignKey<CustomerHasCartDomain>()

Why do you need CartId?
Have you looked at the existing ShoppingCartItems table?  (It may be best to use that structure for your design)
2 meses atrás
New York wrote:
I don't understand you model
ProductInfoDomain as Id column which is PK.  Yet, you are setting up FK with PoductInfoDomain.CartId
.WithColumn(nameof(ProductInfoDomain.CartId)).AsGuid().ForeignKey<CustomerHasCartDomain>()

Why do you need CartId?
Have you looked at the existing ShoppingCartItems table?  (It may be best to use that structure for your design)


I use cartid to make the cart exclusive per customer