使用 EF Core 查询数据库时,可以.Where在执行查询之前轻松有条件地向查询添加子句,例如:
[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();
}
Run Code Online (Sandbox Code Playgroud)
但是,当使用 时.ExecuteUpdate,我看不到如何有条件地链接.SetProperty子句:
[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 …Run Code Online (Sandbox Code Playgroud)