From 17256754c3e03698c3c41ae33cd8283d35566dc4 Mon Sep 17 00:00:00 2001 From: Jon Roberts Date: Tue, 4 Jan 2022 07:56:32 -0600 Subject: [PATCH] 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 --- Readme.md | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/Readme.md b/Readme.md index 16988e24..16fc6018 100644 --- a/Readme.md +++ b/Readme.md @@ -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(); + 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` and will automatically parameterize your query.