public async Task <ElectronicAddress> FindAsync(ElectronicAddress electronicAddress, bool fullMatchOnly = true) { var isCollectionEmpty = await IsEmpty(); if (isCollectionEmpty) { return(null); } var filter = new BsonDocument(); var electronicAddressTask = await Collection().FindAsync(filter); var list = await electronicAddressTask.ToListAsync(); var foundElectronicAddress = list.FirstOrDefault(e => e.Equals(electronicAddress)); if (!ReferenceEquals(foundElectronicAddress, null) || fullMatchOnly) { return(foundElectronicAddress); } foundElectronicAddress = list.FirstOrDefault(e => e.MinEquals(electronicAddress)); return(foundElectronicAddress); }
public async Task <ObjectId> AddOrUpdateAsync(ElectronicAddress electronicAddress) { var upOpt = new UpdateOptions { IsUpsert = true }; var filter = Builders <ElectronicAddress> .Filter.Eq("id", electronicAddress.id); var replaceResult = await Collection().ReplaceOneAsync(filter, electronicAddress, upOpt); if (!replaceResult.IsAcknowledged) { return(ObjectId.Empty); } if (replaceResult.MatchedCount == 0) { return((ObjectId)replaceResult.UpsertedId); } return(electronicAddress.id.Value); }
/// <summary> /// Try a cascading series of attempts to get a matching entity /// </summary> /// <param name="electronicAddress"></param> private async Task <ElectronicAddress> RefreshElectronicAddress(ElectronicAddress electronicAddress) { // First try by id if (electronicAddress.id.HasValue && electronicAddress.id.Value != ObjectId.Empty) { var elecAddrById = await _electronicAddressRepository.GetAsync(electronicAddress.id.Value); if (!ReferenceEquals(elecAddrById, null)) { return(elecAddrById); } } _entityRefreshNeeded = true; // Then try a 'full' match var elecAddrFull = await _electronicAddressRepository.FindAsync(electronicAddress, false); if (!ReferenceEquals(elecAddrFull, null)) { return(elecAddrFull); } // Try a 'min' match var elecAddrMin = await _electronicAddressRepository.FindAsync(electronicAddress, true); if (!ReferenceEquals(elecAddrMin, null)) { // Merge any details from the supplied entity into the found one return(elecAddrMin.Merge(electronicAddress)); } // There is still no match then save the supplied entity first electronicAddress.id = await _electronicAddressRepository.AddOrUpdateAsync(electronicAddress); return(electronicAddress); }