When querying a database with EF Core, it's easy to conditionally add .Where clauses to a query before executing the query, e.g.:
[HttpGet]
public async Task<List<Entity>> GetEntitiesAsync(string? property1, string? property2)
{
var query = _context.Entities.AsNoTracking();
if (property1 != null)
{
query = query.Where(e => e.Property1.Contains(property1));
}
if (property2 != null)
{
query = query.Where(e => e.Property2.Contains(property2));
}
return await query.ToListAsync();
}
However, when using .ExecuteUpdate, I can't see how you would conditionally chain .SetProperty clauses:
[HttpPatch("{id}")]
public async Task<IActionResult> UpdateEntityAsync(int id, Entity entity)
{
var entitiesUpdated = await _context.Entities
.Where(e => e.Id == id)
.ExecuteUpdateAsync(s => s
// How to conditionally chain SetProperty based on
// if entity.Property1 and entity.Property2 are null?
.SetProperty(e => e.Property1, entity.Property1)
.SetProperty(e => e.Property2, entity.Property2)
);
return entitiesUpdated == 1 ? NoContent() : NotFound();
}
You can't use if statements inside the lambda. It needs to be a single expression that evaluates to a SetPropertyCalls<T>. Maybe you could manually create an expression tree, but wouldn't you need to build it on top of the parameter passed into the lambda? Is there an easy way I'm not seeing?
