mirror of
https://github.com/dotnetcore/FreeSql.git
synced 2026-02-20 15:20:56 +08:00
update
64
动态操作.md
64
动态操作.md
@@ -1,3 +1,37 @@
|
||||
## 动态片段
|
||||
|
||||
FreeSql 提供 Where(sql)、GroupBy(sql)、OrderBy(sql)、ToList(sql) 等直接使用 SQL 片段的 API。
|
||||
|
||||
**使用这些 API 时请务必注意SQL注入安全问题。**
|
||||
|
||||
在业务代码中如何防止注入?
|
||||
|
||||
不建议前端直接 POST SQL 到后端使用这些 API,而应该在后端做一层映射,例如:
|
||||
|
||||
```csharp
|
||||
var whereMapping = new Dictionary<string, string>
|
||||
{
|
||||
["where1"] = "a.id > {0}",
|
||||
["where2"] = "len(a.name) > {0}"
|
||||
};
|
||||
var orderByMapping = new Dictionary<string, string>
|
||||
{
|
||||
["order1"] = "a.id asc, a.name desc",
|
||||
["order2"] = "len(a.name) desc"
|
||||
};
|
||||
|
||||
//假设前端 POST 内容是 postWhere=where1&postWhereValue=100&postOrder=order1
|
||||
fsql.Select<Region>()
|
||||
.WhereIf(
|
||||
whereMapping.TryGetValue(postWhere, out var whereSql),
|
||||
string.Format(whereSql, postWhereValue)
|
||||
)
|
||||
.OrderBy(
|
||||
orderByMapping.TryGetValue(postOrder, out var orderSql),
|
||||
orderSql
|
||||
)
|
||||
```
|
||||
|
||||
## 弱类型 CRUD
|
||||
|
||||
```csharp
|
||||
@@ -46,36 +80,6 @@ InsertDict/UpdateDict/DeleteDict/InsertOrUpdateDict 都支持批量操作,对
|
||||
fsql.Select<Region>().Where("a.id > 0") //提示:存在SQL注入安全问题
|
||||
```
|
||||
|
||||
在业务代码中如何防止注入?
|
||||
|
||||
类似 Where(sql)、GroupBy(sql)、OrderBy(sql) 等直接使用 SQL 片段的方法,都不建议前端直接 POST 到后端。
|
||||
|
||||
应该在后端做一层映射,例如:
|
||||
|
||||
```csharp
|
||||
var whereMapping = new Dictionary<string, string>
|
||||
{
|
||||
["where1"] = "a.id > {0}",
|
||||
["where2"] = "len(a.name) > {0}"
|
||||
};
|
||||
var orderByMapping = new Dictionary<string, string>
|
||||
{
|
||||
["order1"] = "a.id asc, a.name desc",
|
||||
["order2"] = "len(a.name) desc"
|
||||
};
|
||||
|
||||
//假设前端 POST 内容是 postWhere=where1&postWhereValue=100&postOrder=order1
|
||||
fsql.Select<Region>()
|
||||
.WhereIf(
|
||||
whereMapping.TryGetValue(postWhere, out var whereSql),
|
||||
string.Format(whereSql, postWhereValue)
|
||||
)
|
||||
.OrderBy(
|
||||
orderByMapping.TryGetValue(postOrder, out var orderSql),
|
||||
orderSql
|
||||
)
|
||||
```
|
||||
|
||||
2、ISelect.WhereDynamicFilter 方法实现动态过滤条件(与前端交互),支持的操作符:
|
||||
|
||||
- Contains/StartsWith/EndsWith/NotContains/NotStartsWith/NotEndsWith:包含/不包含,like '%xx%',或者 like 'xx%',或者 like '%xx'
|
||||
|
||||
Reference in New Issue
Block a user