The common way to delete an entity in Entity Framework is to retrieve the entity from the database into the context and then delete it from the context. Generally to delete the entity in Entity Framework, the developer uses the following.
The code above has one problem; there are two database queries for one operation (one query for retrieving the data from the database and the other to delete the data from the database).
Interception/SQL logging in Entity Framework
Entity Framework 6.0 introduced the feature called "Logging SQL". While working with Entity Framework, it sends commands (or an equivalent SQL query) to the database to do a CRUD operation and this command can be intercepted by application code of Entity Framework. This feature of the Entity Framework is to capture an equivalent SQL query generated by Entity Framework internally and provide it as output.
How to enable SQL logging
The DbContext.Database.Log property can be set to delegate for any method that accepts a string as the parameter. Using this method, all SQL generated by the current context will be logged. For example, the following code can be used to send output to the Console.
The following is the SQL logging output of the code above:
The probable solutions of deleting the entity without retrieving it are given below.
Using the methods described above, we can delete an existing entity without retrieving it from the database and we can gain some performance benefit.