小编TyG*_*y96的帖子

When to use Async methods in EF Core?

I'm building an application with an SQL database, with the following CRUD operations:

public Foo Add(Foo foo)
{
    _dbContext.Foos.Add(foo);
    _dbContext.SaveChanges();
    return foo;
}

public Foo Delete(int id)
{
    Foo foo = _dbContext.Foos.Find(id);
    if(foo != null)
    {
        _dbContext.Foos.Remove(foo);
        _dbContext.SaveChanges();
    }
    return foo;
}
Run Code Online (Sandbox Code Playgroud)

However, some of these methods have asynchronous versions. The following still works:

public async Task<Foo> Add(Foo foo)
{
    await _dbContext.Foos.AddAsync(foo);
    await _dbContext.SaveChangesAsync();
    return foo;
}

public async Task<Foo> Delete(int id)
{
    Foo foo = await _dbContext.Foos.FindAsync(id);
    if(foo != …
Run Code Online (Sandbox Code Playgroud)

c# performance asynchronous entity-framework-core asp.net-core-3.1

8
推荐指数
2
解决办法
7782
查看次数