1
public async Task DeleteAsync(int id)
{
    Food food = await dataContext.Foods.FindAsync(id);
    dataContext.Foods.Remove(food);
        
    await dataContext.SaveChangesAsync();
}

it is CRUD operation for food model. I want to do it without new select.

Paul
  • 4,160
  • 3
  • 30
  • 56

2 Answers2

0

You don't actually need all the fields to delete a record. You only need id. So you can create a simple stub that would only contain id and pass it into Remove method.

 public async Task DeleteAsync(int id)
 {
      var food = new Food { Id = id };
      dataContext.Foods.Remove(food);

      await dataContext.SaveChangesAsync();
 }

You can find more information about it here: https://www.learnentityframeworkcore.com/dbcontext/deleting-data

maxc137
  • 2,291
  • 3
  • 20
  • 32
0

Remove needs an object to remove. So if you want to use Remove, you have to select (or create an object and set the ID as in the answer of Максим Кошевой) the object in your case.

If you want to remove directly, you can type the query like this :

dataContext.Database.ExecuteSqlCommand("DELETE FROM Foods WHERE ID = {0}", id);
//Assuming the ID field's named ID in your Foods table and the table is named Foods (in some cases EF can add s at the end of tables).
Coskun Ozogul
  • 2,389
  • 1
  • 20
  • 32
  • It does need an object, but you can create one and only set Id field into it (see my answer). SQL seems kinda extreme here since this query will need to be maintained manually – maxc137 Oct 13 '20 at 11:20
  • That is what I said exactly, if you want you use Remove method, you need an object. You select or create, your choice. But, if you dont want an object, you can send a delete query. I am not against your answer, it is fine. – Coskun Ozogul Oct 13 '20 at 11:42