How to write an extension for the Entity Framework Core

258 views Asked by At

The actual thing that I need is an effective Delete method for the entities. In other words I would like to be able to write

cntx.Orders.Where(item => item.Category == "Custom1").Delete();

and that is supposed to delete all the records from the table Orders where the Category column value is equal to "Custom1". I don't really care if it will do it right away or after calling cntx.SaveChanges(). And, yes, the query is supposed to be efficient, something like

DELETE FROM Orders WHERE Category = "Custom1"

I know about at least 3 extension libraries for the Entity Framework Core which advertise such abilities but non of them work for Android. Now, I'm thinking how difficult it actually is to write a Delete extension method myself. Can anybody help me with an example? Apparently I should be able to add something to the expression tree which will be called by the framework and in my turn I would generate "DELETE FROM Orders" and then "Where(item => item.Category == "Custom1")" would be replaced by the "WHERE Category = "Custom1""

So, apparently everything should start from

public static class QueryExtension {
   public static void Delete<T>(IQueryable<T> objThis) {
      // The big mystery is what to call here to ensure that "DELETE FROM [TableName]"
      // is entered to the right place of the expression tree and then
      // we somehow need to execute the complete statement here or delegate it to SaveChanges
   }
}

I sort of realize that translation of the expression tree into a SQL statement happens somewhere in the expression visitor. That is most likely wrapped into some kind of statement compiler of the Entity Framework. I have no idea where all those entry points to write an extension like I need.

0

There are 0 answers