public static string InsertNewCustomer(NorthwindEntities db, Customer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException("Customer cannot be null.");
            }

            using (db)
            {
                db.Customers.Add(customer);
                db.Customers.Add(customer);
                db.SaveChanges();

                return customer.CustomerID;
            }
        }
        public static void UpdateCustomerCompanyName(NorthwindEntities db, string customerID, string newCompanyName)
        {
            if (string.IsNullOrWhiteSpace(customerID))
            {
                throw new ArgumentException(string.Format("Invalid ID : {0}.", customerID));
            }

            using (db)
            {
                var customer = db.Customers
                                .FirstOrDefault(c => c.CustomerID == customerID);

                if (customer == null)
                {
                    throw new ArgumentException("No such customer with this id.");
                }

                customer.CompanyName = newCompanyName;
                db.SaveChanges();
            }
        }
        public static void Delete(NorthwindEntities db, string customerID)
        {
            if (string.IsNullOrWhiteSpace(customerID))
            {
                throw new ArgumentException("Id is null, empty or contains only whitespaces.");
            }

            using (db)
            {
                var customer = db.Customers
                                .FirstOrDefault(c => c.CustomerID == customerID);

                if (customer == null)
                {
                    throw new ArgumentException("No such customer with this id.");
                }

                db.Customers.Remove(customer);
                db.SaveChanges();
            }
        }
Example #4
0
        //// To deal with this problem next time use Transactions
        public static void Main()
        {
            var db1 = new NorthwindEntities();
            var db2 = new NorthwindEntities();

            var employeeFromDb1 = db1.Employees.FirstOrDefault();
            var employeeFromDb2 = db2.Employees.FirstOrDefault();

            Console.WriteLine("Name from db1: {0}", employeeFromDb1.FirstName + " " + employeeFromDb1.LastName);
            Console.WriteLine("Name from db2: {0}", employeeFromDb2.FirstName + " " + employeeFromDb2.LastName);

            employeeFromDb1.LastName = "context 1";

            // Second name will overwrite the first.
            employeeFromDb2.LastName = "context 2";

            db1.SaveChanges();
            db2.SaveChanges();

            var dbResult = new NorthwindEntities().Employees.FirstOrDefault();
            Console.WriteLine("\nResult:      : {0}", dbResult.FirstName + " " + dbResult.LastName);
        }