@@ -190,6 +190,7 @@ public Result<Customer> ChangeStatus(CustomerStatus status)
190190 public Result < Customer > AddAddress ( string name , string line1 , string line2 , string postalCode , string city , string country )
191191 {
192192 return this . Change ( )
193+ . Ensure ( _ => ! this . HasDuplicateAddress ( name , line1 , postalCode , city , country ) , "Duplicate address already exists" )
193194 . Add ( e => this . addresses , Address . Create ( name , line1 , line2 , postalCode , city , country ) )
194195 . Register ( e => new CustomerUpdatedDomainEvent ( e ) )
195196 . Apply ( ) ;
@@ -224,7 +225,7 @@ public Result<Address> FindAddress(AddressId id)
224225 {
225226 return this . addresses . AsEnumerable ( ) . Find ( e => e . Id == id )
226227 . Match (
227- some : e => Result < Address > . Success ( e ) ,
228+ some : Result < Address > . Success ,
228229 none : ( ) => Result < Address > . Failure ( )
229230 . WithError ( "Address with specified ID not found" ) ) ;
230231 }
@@ -245,13 +246,26 @@ public Result<Customer> ChangeAddress(AddressId id, string name, string line1, s
245246 {
246247 return this . FindAddress ( id ) . Bind ( e => e
247248 . Change ( )
249+ . Ensure ( _ => ! this . HasDuplicateAddress ( name , line1 , postalCode , city , country , id ) , "Duplicate address already exists" )
248250 . Set ( e => e . ChangeName ( name ) )
249251 . Set ( e => e . ChangeLine1 ( line1 ) )
250252 . Set ( e => e . ChangeLine2 ( line2 ) )
251253 . Set ( e => e . ChangePostalCode ( postalCode ) )
252254 . Set ( e => e . ChangeCity ( city ) )
253255 . Set ( e => e . ChangeCountry ( country ) )
254- . Register ( e => new CustomerUpdatedDomainEvent ( this ) )
256+ . Register ( e => new CustomerUpdatedDomainEvent ( this ) ) // TODO: the event should register on the Customer aggregate, not the Address entity
257+ //.Register(c, e=> new CustomerUpdatedDomainEvent(this))
255258 . Apply ( ) . Wrap ( this ) ) ;
256259 }
260+
261+ private bool HasDuplicateAddress ( string name , string line1 , string postalCode , string city , string country , AddressId excludeId = null )
262+ {
263+ return this . addresses . Any ( a =>
264+ ( excludeId == null || a . Id != excludeId ) &&
265+ a . Name == name &&
266+ a . Line1 == line1 &&
267+ a . PostalCode == postalCode &&
268+ a . City == city &&
269+ a . Country == country ) ;
270+ }
257271}
0 commit comments