Data Haunting

Easy Solutions Destination

By

Entity framework delete object without retrieving it

In Entity Framework to delete an Object, we first fetched the object and than delete that particular object or record. This one result in to performance penalty as there are two SQL query executed first one for “Select” query and second one for “Delete” query. In Entity Framework 6.0 or above Microsoft provide solution to delete an object(record) with out retrieving or fetching it.

Conventional way to delete an object in Entity Framework

General way to delete an object in Entity Framework is as given.

But problem with Conventional way to delete an object is that it first fetch the record from Database using Select query and than perform delete operation. If you optimize sql query using either sql profiler or any other tools than you can see following two query which results into performance penalty.

Delete an object without fetching by changing it’s state

Dbcontext has method Entry and Entry in that pass EntityState as Deleted. As these method get a DBEntityEntry for the given Entity and enable to perform the action on Entity just by changing the state to Delete as given below.

Now if you inspect your query in SQL Profiler than you will find that you Delete operation on object or records is done with out fetching or retrieving data from Database and out put log will be as given below.

Delete an object without fetching by executing SQL query

In Entity Database context record or object can be deleted without fetching just by executing SQL query using ExecuteSqlCommand as given below.

Delete Multiple records without fetching by executing SQL query

Using ExecuteSqlCommand can delete multiple records by passing object array of deleting id in once.

While inspecting in Sql Profiler above query perform only delete operation with out using select statements.

What is your opinion ?

Here we have seen how we can achieve the Delete functionality of Entity Framework as provided in SQL Server without fetching records for that Entity. I hope this will be useful in your Entity Framework project to achieve better performance. If you have any query and question, you can comment or you can mail me.

Leave a Reply