mirror of
https://github.com/DapperLib/Dapper.git
synced 2026-10-17 05:12:13 +08:00
Document usage of IDynamicParameters in more detail (#1707)
Considering all of the inquiries on StackOverflow about DynamicParameters, there should probably be a simple overview in the documentation. Examples: - https://stackoverflow.com/questions/12723922/dapper-adddynamicparams-for-in-statement-with-dynamic-parameter-name - https://stackoverflow.com/questions/43412455/dapper-with-sql-query-dynamic-parameters - https://stackoverflow.com/questions/38443739/passing-dynamically-created-sql-parameters-into-dapper-as-an-anonymous-type - https://stackoverflow.com/questions/62448900/how-do-i-loop-through-dapper-dynamic-query-results-using-strings-as-parameters - https://stackoverflow.com/questions/36735189/dapper-dynamicparameters-returning-error
This commit is contained in:
@@ -187,12 +187,35 @@ Alternatively, you might prefer Frans Bouma's [RawDataAccessBencher](https://git
|
||||
Parameterized queries
|
||||
---------------------
|
||||
|
||||
Parameters are passed in as anonymous classes. This allow you to name your parameters easily and gives you the ability to simply cut-and-paste SQL snippets and run them in your db platform's Query analyzer.
|
||||
Parameters are usually passed in as anonymous classes. This allow you to name your parameters easily and gives you the ability to simply cut-and-paste SQL snippets and run them in your db platform's Query analyzer.
|
||||
|
||||
```csharp
|
||||
new {A = 1, B = "b"} // A will be mapped to the param @A, B to the param @B
|
||||
```
|
||||
Parameters can also be built up dynamically using the DynamicParameters class. This allows for building a dynamic SQL statement while still using parameters for safety and performance.
|
||||
|
||||
```csharp
|
||||
var sqlPredicates = new List<string>();
|
||||
var queryParams = new DynamicParameters();
|
||||
if (boolExpression)
|
||||
{
|
||||
sqlPredicates.Add("column1 = @param1");
|
||||
queryParams.Add("param1", dynamicValue1, System.Data.DbType.Guid);
|
||||
} else {
|
||||
sqlPredicates.Add("column2 = @param2");
|
||||
queryParams.Add("param2", dynamicValue2, System.Data.DbType.String);
|
||||
}
|
||||
```
|
||||
|
||||
DynamicParameters also supports copying multiple parameters from existing objects of different types.
|
||||
|
||||
```csharp
|
||||
var queryParams = new DynamicParameters(objectOfType1);
|
||||
queryParams.AddDynamicParams(objectOfType2);
|
||||
```
|
||||
|
||||
When an object that implements the `IDynamicParameters` interface passed into `Execute` or `Query` functions, parameter values will be extracted via this interface. Obviously, the most likely object class to use for this purpose would be the built-in `DynamicParameters` class.
|
||||
|
||||
List Support
|
||||
------------
|
||||
Dapper allows you to pass in `IEnumerable<int>` and will automatically parameterize your query.
|
||||
|
||||
Reference in New Issue
Block a user