예제 #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 RopResult <Unit, DomainMessage> Upsert(Customer customer)
        {
            if (customer == null)
            {
                throw new ArgumentNullException("customer");
            }

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

            return(Rop.Match(existingDbCust,
                             success =>
            {
                // update
                db.Update(newDbCust);

                // check for changed email
                if (!customer.EmailAddress.Equals(success.EmailAddress))
                {
                    // return a Success with the extra event
                    var msg = DomainMessage.EmailAddressChanged(success.EmailAddress, customer.EmailAddress);
                    return Rop.SucceedWithMsg <Unit, DomainMessage>(Unit.Instance, msg);
                }
                else
                {
                    // return a Success with no extra event
                    return Rop.Succeed <Unit, DomainMessage>(Unit.Instance);
                }
            },
                             failure =>
            {
                // insert
                db.Insert(newDbCust);

                // return a Success
                return Rop.Succeed <Unit, DomainMessage>(Unit.Instance);
            }));
        }