entity-framework-core - 如何为 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 语句的转换发生在表达式访问者的某个地方。这很可能包含在实体框架的某种语句编译器中。我不知道所有这些入口点在哪里编写我需要的扩展。
解决方案
推荐阅读
- c# - 如何使 dll 中的代码适应主代码?
- vb.net - 如何使用带方括号的 SelectToken?
- python - Python如何从excel中迭代特定行
- c# - 最小化/最大化表单会导致在焦点中设置多个组合框。这里发生了什么?
- javascript - 从节点和 Typescript 应用程序连接 Vertica DB
- javascript - 分配前使用的变量
- rest - 使用相同的 REST API 识别多个微服务的最佳实践?
- java - 映射后获取映射
- javascript - react-native-navigation 和 react-navigation 有什么区别?
- reactjs - React 文本字段的默认值不会被覆盖