Exemplo n.º 1
0
 // Preventing index break
 public bool IsProductRepeated()
 {
     using (ApplicationDbContext db = new ApplicationDbContext())
     {
         Product productInDbRepeated = db.Products.FirstOrDefault(x => x.Title == Title && x.Id != Id);
         // Preventing index break in memory. It doesn't exist there, but we're preventing as well
         Product productInMemoryRepeated = ProductsInMemory.FirstOrDefault(x => x.Title == Title && x.Id != Id);
         return(productInDbRepeated != null || productInMemoryRepeated != null);
     }
 }
Exemplo n.º 2
0
        public int?CreateOrEditProductInMemory()
        {
            try
            {
                int productId = default;
                if (IsProductRepeated())
                {
                    return(default(int));
                }
                Product productSavedInMemory = ProductsInMemory.FirstOrDefault(x => x.Id == Id);

                if (productSavedInMemory != null)
                {
                    productSavedInMemory.Title  = Title;
                    productSavedInMemory.Number = Number;
                    productSavedInMemory.Price  = Price;
                    // Replacing the object edited in memory according his position
                    ProductsInMemory[ProductsInMemory.IndexOf(productSavedInMemory)] = productSavedInMemory;
                    productId = productSavedInMemory.Id;
                }
                else
                {
                    // Getting products amount for Id assignment and put them negative for avoid inconsistencies against Id from db when the user is editing
                    Product newProduct = new Product()
                    {
                        Id     = (ProductsInMemory.Count() + 1) * -1,
                        Title  = Title,
                        Number = Number,
                        Price  = Price
                    };
                    ProductsInMemory.Add(newProduct);
                    productId = newProduct.Id;
                }
                memoryCache.Set(CacheKey, ProductsInMemory, CacheItemPolicy);
                return(productId);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(null);
            }
        }