如果没有 new select,我怎么能写出更简单的代码呢?

how can i write more simple code without new select?

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

是食物模型的CRUD操作。我想在没有 new select.

的情况下进行

您实际上不需要所有字段来删除记录。你只需要身份证。因此,您可以创建一个仅包含 id 的简单存根并将其传递给 Remove 方法。

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

      await dataContext.SaveChangesAsync();
 }

您可以在此处找到更多相关信息:https://www.learnentityframeworkcore.com/dbcontext/deleting-data

删除需要删除一个对象。因此,如果您想使用 Remove,您必须 select(或创建一个对象并设置 ID,如 Максим Кошевой 的答案)您的对象。

如果你想直接删除,你可以这样输入查询:

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).