Exemplo n.º 1
0
        /// <summary>
        /// Insert/update the customer
        /// If it already exists, update it, otherwise insert it.
        /// If the email address has changed, raise a EmailAddressChanged event on DomainEvents
        /// </summary>
        public void Upsert(Customer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }

            var db             = new DbContext();
            var existingDbCust = GetById(customer.Id);
            var newDbCust      = ToDbCustomer(customer);

            if (existingDbCust == null)
            {
                // insert
                db.Insert(newDbCust);

                // Note that this code does not trap exceptions coming from the database. What would it do with them?
                // Compare with the F# version, where errors are alway returned from the call
            }
            else
            {
                // update
                db.Update(newDbCust);

                // check for changed email
                if (!customer.EmailAddress.Equals(existingDbCust.EmailAddress))
                {
                    // Generate a event
                    // Note that this code is buried deep in a class and is not obvious
                    // It is also hard to turn on and off (eg for batch updates) without adding extra complications
                    //
                    // Compare this with the F# version, when an event is returned from the call itself.
                    DomainEvents.OnEmailAddressChanged(existingDbCust.EmailAddress, customer.EmailAddress);
                }
            }
        }