Exemplo n.º 1
0
        public void AddCustomerTest()
        {
            using (var context = new NorthWindContext(ContextInMemoryOptions()))
            {
                var contact = new Contact()
                {
                    FirstName = "Karen",
                    LastName  = "Payne"
                };
                context.Entry(contact).State = EntityState.Added;

                var customer = new Customer()
                {
                    CompanyName = "Karen's coffee shop",
                    ContactIdentifierNavigation = contact,
                    CountryIdentfier            = 20
                };
                context.Entry(customer).State = EntityState.Added;

                var saveChangesCount = context.SaveChanges();

                Assert.IsTrue(saveChangesCount == 2,
                              "Expect one customer and one contact to be added.");
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// 儲存與更新
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        public async Task <Employee> SaveAsync(Employee model)
        {
            // 如果(PK)不為0,代表為更新
            if (model.EmployeeID != 0)
            {
                //更新
                _db.Entry(model).State = System.Data.Entity.EntityState.Modified;
            }
            else
            {
                //新增
                _db.Employees.Add(model);
            }

            try
            {
                await _db.SaveChangesAsync();

                return(model);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!entityExists(model.EmployeeID))
                {
                    return(null);
                }
                else
                {
                    throw;
                }
            }
        }
        public void ApplyDiscount2(int pCustomerIdentifier, float pCurrentDiscount, float pNewDiscount)
        {
            using (var context = new NorthWindContext())
            {
                context.Configuration.AutoDetectChangesEnabled = false;
                context.Configuration.LazyLoadingEnabled       = false;

                var orderDetailsResults = (from order in context.Orders
                                           join orderDetail in context.Order_Details on order.OrderID equals orderDetail.OrderID
                                           where order.CustomerIdentifier == pCustomerIdentifier
                                           select orderDetail).AsNoTracking().ToList();

                orderDetailsResults = orderDetailsResults
                                      .DistinctBy(details => details.OrderID)
                                      .Where(details => details.Discount == pCurrentDiscount)
                                      .ToList();

                foreach (var item in orderDetailsResults)
                {
                    item.Discount             = pNewDiscount;
                    context.Entry(item).State = EntityState.Modified;
                }

                Console.WriteLine(context.SaveChanges());
            }
        }
        public async Task <IActionResult> PutProducts(int id, Products products)
        {
            if (id != products.ProductId)
            {
                return(BadRequest());
            }

            _context.Entry(products).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductsExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
 public void DeleteProduct(Product product)
 {
     using (var context = new NorthWindContext())
     {
         context.Entry(product).State = EntityState.Deleted;
         context.SaveChanges();
     }
 }
 /// <summary>
 /// Example for updating a disconnected entry indicating
 /// this is a modification by setting State property to Modified.
 /// </summary>
 /// <param name="product"></param>
 /// <param name="discontinued"></param>
 public void SaveProduct(Product product, bool discontinued)
 {
     using (var context = new NorthWindContext())
     {
         product.Discontinued         = discontinued;
         context.Entry(product).State = EntityState.Modified;
         context.SaveChanges();
     }
 }
 public void Update(TEntity entity)
 {
     using (NorthWindContext context = new NorthWindContext())
     {
         var updatedCategory = context.Entry(entity);
         updatedCategory.State = EntityState.Modified;
         context.SaveChanges();
     }
 }
Exemplo n.º 8
0
 public ActionResult Edit([Bind(Include = "ProductId,ProductName,UnitsInStock,UnitPrice,Discontinued,CategoryID")] Product product)
 {
     if (ModelState.IsValid)
     {
         db.Entry(product).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(product));
 }
        /// <summary>
        /// Demonstrates multi-purpose method for add or update
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public int AddOrUpdate(Product product)
        {
            using (var context = new NorthWindContext())
            {
                context.Entry(product).State = product.ProductID == 0 ?
                                               EntityState.Added :
                                               EntityState.Modified;

                return(context.SaveChanges());
            }
        }
        /// <summary>
        /// Create a new Product and add the new Product
        /// to the DbContext along with indicating this
        /// item is a new entity via the entry state
        /// </summary>
        public void AddProduct1()
        {
            var product = new Product()
            {
                ProductName = "Headphones",
                CategoryID  = 1,
                UnitPrice   = 17.99M
            };

            using (var context = new NorthWindContext())
            {
                context.Entry(product).State = EntityState.Added;
            }
        }
Exemplo n.º 11
0
            public static void Ders6Delete(NorthWindContext db)
            {
                var p = db.Products.Find(89);

                if (p != null)
                {
                    db.Products.Remove(p);
                    db.SaveChanges();
                }

                //metot2
                var p2 = new Product()
                {
                    ProductId = 90
                };

                db.Entry(p2).State = EntityState.Deleted;
                db.SaveChanges();

                //çoklu silme
                var p3 = new Product()
                {
                    ProductId = 92
                };
                var p4 = new Product()
                {
                    ProductId = 93
                };
                var p5 = new Product()
                {
                    ProductId = 94
                };

                var delproducts = new List <Product>()
                {
                    p3, p4, p5
                };

                db.RemoveRange(delproducts);
                db.SaveChanges();
            }
        public void ApplyDiscount1(int pCustomerIdentifier, float pCurrentDiscount, float pNewDiscount)
        {
            using (var context = new NorthWindContext())
            {
                var orderDetailsResults = (from order in context.Orders
                                           join orderDetail in context.Order_Details on order.OrderID equals orderDetail.OrderID
                                           where order.CustomerIdentifier == pCustomerIdentifier
                                           select orderDetail)
                                          .DistinctBy(details => details.OrderID)
                                          .Where(details => details.Discount == pCurrentDiscount)
                                          .ToList();

                foreach (var item in orderDetailsResults)
                {
                    item.Discount             = pNewDiscount;
                    context.Entry(item).State = EntityState.Modified;
                }

                Console.WriteLine(context.SaveChanges());
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Save a single <see cref="Employee"/>
        /// </summary>
        /// <param name="employee"><see cref="Employee"/></param>
        /// <returns>1 for success, other values failure</returns>
        public static bool SaveEmployee(Employee employee)
        {
            /*
             * Connect to database
             */
            using var context          = new NorthWindContext();
            context.SavedChanges      += ContextOnSavedChanges;
            context.SaveChangesFailed += ContextOnSaveChangesFailed;

            /*
             * Tell Entity Framework we are saving changes to an existing record,
             */
            context.Entry(employee).State = EntityState.Modified;

            /*
             * SaveChanges returns count of changes e.g. one record = 1, two records = 2 etc.
             * While 0 means nothing updated.
             *
             * Contrary to the above the ChangeTracker for EF Core will return 1 even if no
             * properties changed.
             */
            return(context.SaveChanges() == 1);
        }
Exemplo n.º 14
0
 public void AddOrUpdateProduct(Product prod)
 {
     _context.Entry(prod).State = EntityState.Modified;
     _context.SaveChanges();
 }