首页 > 解决方案 > 如何为 Entity Framework Core 编写扩展

问题描述

我真正需要的是实体的有效删除方法。换句话说,我希望能够写

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

并且应该从表 Orders 中删除 Category 列值等于“Custom1”的所有记录。我真的不在乎它是立即执行还是在调用cntx.SaveChanges() 之后执行。而且,是的,查询应该是有效的,比如

DELETE FROM Orders WHERE Category = "Custom1"

我知道 Entity Framework Core 的至少 3 个扩展库宣传了这些功能,但它们都不适用于 Android。现在,我在想自己编写一个 Delete 扩展方法实际上是多么困难。有人可以帮我举个例子吗?显然我应该能够向框架调用的表达式树添加一些东西,然后我会生成“DELETE FROM Orders”,然后生成“Where(item => item.Category == "Custom1")”替换为“WHERE Category = “Custom1””

所以,显然一切都应该从

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
   }
}

我有点意识到表达式树到 SQL 语句的转换发生在表达式访问者的某个地方。这很可能包含在实体框架的某种语句编译器中。我不知道所有这些入口点在哪里编写我需要的扩展。

标签: entity-framework-coreentity-framework-extensions

解决方案


推荐阅读