小编Han*_*tie的帖子

如何使用 Entity Framework Core ExecuteUpdate 有条件地 SetProperty?

使用 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)

c# entity-framework-core

6
推荐指数
1
解决办法
3620
查看次数

标签 统计

c# ×1

entity-framework-core ×1