实体框架不会抛出错误,但我在调试模式下看到它

问题描述 投票:0回答:1

我的以下代码错误地包含

.Equals(userUserId, StringComparison.OrdinalIgnoreCase))

我的问题是为什么代码不抛出异常。

CreateOrUpdateUserAsync()
方法在行中退出

User? user = query.FirstOrDefault();

但是,控制器中的 try 确实捕获了错误。为什么不呢?

控制器:

[HttpPut]
[Route("user")]
public ActionResult UpdateUser([FromBody] Useruser)
{
    if (user == null) return BadRequest("Invalid user");

    try
    {
        this._myUserRepository.CreateOrUpdateUserAsync(userS);

        return StatusCode(((int)HttpStatusCode.NoContent));
    }
    catch (Exception e)
    {
        return StatusCode((int)HttpStatusCode.InternalServerError, e);
    }
}

存储库:

错误:

LINQ 表达式 'DbSet()
.Where(u => u.UserId.Equals(value: __user_UserId_0, ComparisonType: OrdinalIgnoreCase))' 无法翻译。

其他信息:不支持使用“StringComparison”参数翻译“string.Equals”重载。请参阅 https://go.microsoft.com/fwlink/?linkid=2129535 了解更多信息。以可翻译的形式重写查询,或者通过插入对“AsEnumerable”、“AsAsyncEnumerable”、“ToList”或“ToListAsync”的调用来显式切换到客户端计算。请参阅 https://go.microsoft.com/fwlink/?linkid=2101038 了解更多信息。

c# async-await entity-framework-core
1个回答
4
投票

您应该

await
您的
async
方法调用:

public async ActionResult UpdateUser([FromBody] UserSetting userSetting)
{
    // ...
    try
    {
        await this._myUserRepository.CreateOrUpdateUserSettingAsync(userSetting);

        // ...
    }
    catch (Exception e)
    {
        // ...
    }
}

否则,这基本上是一个“即发即忘”的任务,可能会导致多种问题(例如未观察到的异常,或“过早”处置资源,如

DbContext

© www.soinside.com 2019 - 2024. All rights reserved.