MongoRepository icon indicating copy to clipboard operation
MongoRepository copied to clipboard

QUESTION. UpdateOrInsertOneAsync

Open scharada opened this issue 2 years ago • 1 comments

Hi John, is there an example on how to use UpdateOrInsertOneAsync ? thanks

scharada avatar Jan 11 '24 12:01 scharada

Hi @scharada

In a project I'm involved in, we're using it when importing products from a webshop to a local database. When importing a product, we don't know beforehand if it already exists in the database. If it doesn't exist, we want to insert it. If it already exists, we want to know which product category it belongs to:

var upsertedProduct = await _productRepository.UpdateOrInsertOneAsync(
	filter: x => x.Id == newProduct.Id || x.Sku == newProduct.Sku,
	update: x => x
		.Set(y => y.DescriptionHtml, newProduct.DescriptionHtml)
		.Set(y => y.Sku, newProduct.Sku)
                /* set more fields */,
	entityToInsertIfNoMatch: newProduct,
	returnProjection: x => new MatchedProduct(x.Id, x.ProductCategoryId)

johnknoop avatar Jan 11 '24 12:01 johnknoop