문제

I am using NopCommerce. I have created new table named "ProductViewDetails". I have tried to insert/update record in this table. When i tried to insert new record in the table,New record inserted successfully. but when i tried to update operation ,Method "UpdateData" executed successfully but record did not update.

Code :

    public void IncremementViews(int productId)
    {
    ProductViewDetails ProductDetails = new ProductViewDetails();
    ProductDetails.Id = 5;
    ProductDetails.ProductId = 1;
    ProductDetails.NumberOfViews = 10; 

    UpdateData(ProductDetails);
    }  

    public void UpdateData(ProductViewDetails productDetails)
    {         
       _productViewDetails.Update(productDetails);

    }  

Update Method Code :

   public partial class EfRepository<T> : IRepository<T> where T : BaseEntity
   {
    private readonly IDbContext _context;
    private IDbSet<T> _entities;

    public void Update(T entity)  
    {
        try
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            this._context.SaveChanges();
        }
        catch (DbEntityValidationException dbEx)
        {
            var msg = string.Empty;

            foreach (var validationErrors in dbEx.EntityValidationErrors)
                foreach (var validationError in validationErrors.ValidationErrors)
                    msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);

            var fail = new Exception(msg, dbEx);
            //Debug.WriteLine(fail.Message, fail);
            throw fail;
        }
    }
   }

What is the problem?

도움이 되었습니까?

해결책

NopCommerce use entity framework with lazy loading and proxied entities for tracking changes, when you instantiate a new entity (as in new ProductViewDetails()) the entity framework context does know nothing about that entity and the context can´t track any changes.

  • If the entity exists previously get it from the repository with GetById method instead of instantiating it, the context will return and attached and proxied entity so the context will tack every change you do and when you call Update all the changes will be save.
  • If your entity is a new one you should call Add method of the repository.

다른 팁

try this

ProductViewDetails ProductDetails = new ProductViewDetails();

/make this function in services and call this and function that retrieve required ProductDetails record/

ProductDetails =_MostViewedProductService.GetMostViewedProductById(productId);
                        UpdateData(ProductDetails);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top