Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove row asynchronously using Entity Framework

I'm still pretty new at async so I'm not sure whether what I'm doing is redundant or not. The following removes a row from a database:

public static async Task Remove(int id)
{
    using (var ctx = new StoreContext())
    {
        ctx.Products.Remove(await ctx.Products.SingleOrDefaultAsync(x => x.ID == id));
        await ctx.SaveChangesAsync();
    }
}

Should I be awaiting here twice or is there no point? As far as I know, both awaits improve responsiveness, while .Remove itself "blocks" responsiveness for a practically unnoticeable amount of time, is that correct?

like image 371
Joe Defill Avatar asked Dec 11 '18 21:12

Joe Defill


People also ask

How do I delete a row in Entity Framework?

Delete a Record In Connected Scenario, you can use the Remove or RemoveRange method to mark the record as Deleted . In Disconnected Scenario, you can attach it to the context and set its state as Deleted . Calling SaveChanges will send the delete query to the database.

How do I remove all records from a table in Entity Framework?

Table select o; foreach (var row in rows) { dataDb. Table. Remove(row); } dataDb. SaveChanges();

When to use async EF Core?

Asynchronous operations avoid blocking a thread while the query is executed in the database. Async operations are important for keeping a responsive UI in rich client applications, and can also increase throughput in web applications where they free up the thread to service other requests in web applications.

What is FirstOrDefaultAsync C#?

FirstOrDefaultAsync<TSource>(IQueryable<TSource>)Asynchronously returns the first element of a sequence, or a default value if the sequence contains no elements. C# Copy.


1 Answers

In your case async/await has nothing to do with how fast something executes. It is used to suspend the thread while the I/O completes so the OS can reuse it for whatever else needs a thread at the moment. In short it is all about scalability. The code above makes 2 I/O calls, one for retrieval and one for deletion (when calling SaveChangesAsync).

You could simplify this and just make 1 call for deletion but that has nothing to do with async/await. In the above code there is no reason to go to the DB first if you already know the primary key (assuming here ID is the primary key).

public static async Task Remove(int id)
{
    using (var ctx = new StoreContext())
    {
        var product = new Product { ID = id};
        ctx.Products.Attach(product);
        ctx.Products.Remove(product);
        await ctx.SaveChangesAsync();
    }
}

As far as DbSet<T>.Remove it internally "queues" a delete operation that is then executed when you call SaveChanges or SaveChangesAsync. It does not "block" anything but maybe you should elaborate what you mean by the word block if you believe otherwise.

like image 100
Igor Avatar answered Nov 15 '22 08:11

Igor