├── .gitattributes
├── .gitignore
├── DapperHelperDemo.sln
├── DapperHelperDemo
├── DapperHelper.cs
├── DapperHelperDemo.csproj
├── DatabaseService.cs
├── Models
│ └── User.cs
└── Program.cs
└── README.md
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Build results
17 | [Dd]ebug/
18 | [Dd]ebugPublic/
19 | [Rr]elease/
20 | [Rr]eleases/
21 | x64/
22 | x86/
23 | [Aa][Rr][Mm]/
24 | [Aa][Rr][Mm]64/
25 | bld/
26 | [Bb]in/
27 | [Oo]bj/
28 | [Ll]og/
29 |
30 | # Visual Studio 2015/2017 cache/options directory
31 | .vs/
32 | # Uncomment if you have tasks that create the project's static files in wwwroot
33 | #wwwroot/
34 |
35 | # Visual Studio 2017 auto generated files
36 | Generated\ Files/
37 |
38 | # MSTest test Results
39 | [Tt]est[Rr]esult*/
40 | [Bb]uild[Ll]og.*
41 |
42 | # NUNIT
43 | *.VisualState.xml
44 | TestResult.xml
45 |
46 | # Build Results of an ATL Project
47 | [Dd]ebugPS/
48 | [Rr]eleasePS/
49 | dlldata.c
50 |
51 | # Benchmark Results
52 | BenchmarkDotNet.Artifacts/
53 |
54 | # .NET Core
55 | project.lock.json
56 | project.fragment.lock.json
57 | artifacts/
58 |
59 | # StyleCop
60 | StyleCopReport.xml
61 |
62 | # Files built by Visual Studio
63 | *_i.c
64 | *_p.c
65 | *_h.h
66 | *.ilk
67 | *.meta
68 | *.obj
69 | *.iobj
70 | *.pch
71 | *.pdb
72 | *.ipdb
73 | *.pgc
74 | *.pgd
75 | *.rsp
76 | *.sbr
77 | *.tlb
78 | *.tli
79 | *.tlh
80 | *.tmp
81 | *.tmp_proj
82 | *_wpftmp.csproj
83 | *.log
84 | *.vspscc
85 | *.vssscc
86 | .builds
87 | *.pidb
88 | *.svclog
89 | *.scc
90 |
91 | # Chutzpah Test files
92 | _Chutzpah*
93 |
94 | # Visual C++ cache files
95 | ipch/
96 | *.aps
97 | *.ncb
98 | *.opendb
99 | *.opensdf
100 | *.sdf
101 | *.cachefile
102 | *.VC.db
103 | *.VC.VC.opendb
104 |
105 | # Visual Studio profiler
106 | *.psess
107 | *.vsp
108 | *.vspx
109 | *.sap
110 |
111 | # Visual Studio Trace Files
112 | *.e2e
113 |
114 | # TFS 2012 Local Workspace
115 | $tf/
116 |
117 | # Guidance Automation Toolkit
118 | *.gpState
119 |
120 | # ReSharper is a .NET coding add-in
121 | _ReSharper*/
122 | *.[Rr]e[Ss]harper
123 | *.DotSettings.user
124 |
125 | # JustCode is a .NET coding add-in
126 | .JustCode
127 |
128 | # TeamCity is a build add-in
129 | _TeamCity*
130 |
131 | # DotCover is a Code Coverage Tool
132 | *.dotCover
133 |
134 | # AxoCover is a Code Coverage Tool
135 | .axoCover/*
136 | !.axoCover/settings.json
137 |
138 | # Visual Studio code coverage results
139 | *.coverage
140 | *.coveragexml
141 |
142 | # NCrunch
143 | _NCrunch_*
144 | .*crunch*.local.xml
145 | nCrunchTemp_*
146 |
147 | # MightyMoose
148 | *.mm.*
149 | AutoTest.Net/
150 |
151 | # Web workbench (sass)
152 | .sass-cache/
153 |
154 | # Installshield output folder
155 | [Ee]xpress/
156 |
157 | # DocProject is a documentation generator add-in
158 | DocProject/buildhelp/
159 | DocProject/Help/*.HxT
160 | DocProject/Help/*.HxC
161 | DocProject/Help/*.hhc
162 | DocProject/Help/*.hhk
163 | DocProject/Help/*.hhp
164 | DocProject/Help/Html2
165 | DocProject/Help/html
166 |
167 | # Click-Once directory
168 | publish/
169 |
170 | # Publish Web Output
171 | *.[Pp]ublish.xml
172 | *.azurePubxml
173 | # Note: Comment the next line if you want to checkin your web deploy settings,
174 | # but database connection strings (with potential passwords) will be unencrypted
175 | *.pubxml
176 | *.publishproj
177 |
178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
179 | # checkin your Azure Web App publish settings, but sensitive information contained
180 | # in these scripts will be unencrypted
181 | PublishScripts/
182 |
183 | # NuGet Packages
184 | *.nupkg
185 | # The packages folder can be ignored because of Package Restore
186 | **/[Pp]ackages/*
187 | # except build/, which is used as an MSBuild target.
188 | !**/[Pp]ackages/build/
189 | # Uncomment if necessary however generally it will be regenerated when needed
190 | #!**/[Pp]ackages/repositories.config
191 | # NuGet v3's project.json files produces more ignorable files
192 | *.nuget.props
193 | *.nuget.targets
194 |
195 | # Microsoft Azure Build Output
196 | csx/
197 | *.build.csdef
198 |
199 | # Microsoft Azure Emulator
200 | ecf/
201 | rcf/
202 |
203 | # Windows Store app package directories and files
204 | AppPackages/
205 | BundleArtifacts/
206 | Package.StoreAssociation.xml
207 | _pkginfo.txt
208 | *.appx
209 |
210 | # Visual Studio cache files
211 | # files ending in .cache can be ignored
212 | *.[Cc]ache
213 | # but keep track of directories ending in .cache
214 | !?*.[Cc]ache/
215 |
216 | # Others
217 | ClientBin/
218 | ~$*
219 | *~
220 | *.dbmdl
221 | *.dbproj.schemaview
222 | *.jfm
223 | *.pfx
224 | *.publishsettings
225 | orleans.codegen.cs
226 |
227 | # Including strong name files can present a security risk
228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
229 | #*.snk
230 |
231 | # Since there are multiple workflows, uncomment next line to ignore bower_components
232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
233 | #bower_components/
234 |
235 | # RIA/Silverlight projects
236 | Generated_Code/
237 |
238 | # Backup & report files from converting an old project file
239 | # to a newer Visual Studio version. Backup files are not needed,
240 | # because we have git ;-)
241 | _UpgradeReport_Files/
242 | Backup*/
243 | UpgradeLog*.XML
244 | UpgradeLog*.htm
245 | ServiceFabricBackup/
246 | *.rptproj.bak
247 |
248 | # SQL Server files
249 | *.mdf
250 | *.ldf
251 | *.ndf
252 |
253 | # Business Intelligence projects
254 | *.rdl.data
255 | *.bim.layout
256 | *.bim_*.settings
257 | *.rptproj.rsuser
258 | *- Backup*.rdl
259 |
260 | # Microsoft Fakes
261 | FakesAssemblies/
262 |
263 | # GhostDoc plugin setting file
264 | *.GhostDoc.xml
265 |
266 | # Node.js Tools for Visual Studio
267 | .ntvs_analysis.dat
268 | node_modules/
269 |
270 | # Visual Studio 6 build log
271 | *.plg
272 |
273 | # Visual Studio 6 workspace options file
274 | *.opt
275 |
276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
277 | *.vbw
278 |
279 | # Visual Studio LightSwitch build output
280 | **/*.HTMLClient/GeneratedArtifacts
281 | **/*.DesktopClient/GeneratedArtifacts
282 | **/*.DesktopClient/ModelManifest.xml
283 | **/*.Server/GeneratedArtifacts
284 | **/*.Server/ModelManifest.xml
285 | _Pvt_Extensions
286 |
287 | # Paket dependency manager
288 | .paket/paket.exe
289 | paket-files/
290 |
291 | # FAKE - F# Make
292 | .fake/
293 |
294 | # JetBrains Rider
295 | .idea/
296 | *.sln.iml
297 |
298 | # CodeRush personal settings
299 | .cr/personal
300 |
301 | # Python Tools for Visual Studio (PTVS)
302 | __pycache__/
303 | *.pyc
304 |
305 | # Cake - Uncomment if you are using it
306 | # tools/**
307 | # !tools/packages.config
308 |
309 | # Tabs Studio
310 | *.tss
311 |
312 | # Telerik's JustMock configuration file
313 | *.jmconfig
314 |
315 | # BizTalk build output
316 | *.btp.cs
317 | *.btm.cs
318 | *.odx.cs
319 | *.xsd.cs
320 |
321 | # OpenCover UI analysis results
322 | OpenCover/
323 |
324 | # Azure Stream Analytics local run output
325 | ASALocalRun/
326 |
327 | # MSBuild Binary and Structured Log
328 | *.binlog
329 |
330 | # NVidia Nsight GPU debugger configuration file
331 | *.nvuser
332 |
333 | # MFractors (Xamarin productivity tool) working folder
334 | .mfractor/
335 |
336 | # Local History for Visual Studio
337 | .localhistory/
338 |
339 | # BeatPulse healthcheck temp database
340 | healthchecksdb
--------------------------------------------------------------------------------
/DapperHelperDemo.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.30114.105
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DapperHelperDemo", "DapperHelperDemo\DapperHelperDemo.csproj", "{9A6E2871-88A1-4668-A4C2-BA0118937371}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {9A6E2871-88A1-4668-A4C2-BA0118937371}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {9A6E2871-88A1-4668-A4C2-BA0118937371}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {9A6E2871-88A1-4668-A4C2-BA0118937371}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {9A6E2871-88A1-4668-A4C2-BA0118937371}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {7423AFCC-7035-4841-9AFE-E4E64CD0F90E}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/DapperHelperDemo/DapperHelper.cs:
--------------------------------------------------------------------------------
1 | using Dapper;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Data;
5 | using System.Text;
6 |
7 | namespace DapperHelperDemo
8 | {
9 | ///
10 | /// The DapperHelper manages the base validation of input values and allows for the easy generation of well formed Insert and Update statements
11 | ///
12 | public class DapperHelper
13 | {
14 | private readonly Dictionary _parameters = new Dictionary();
15 | private readonly SortedDictionary _conditionalParameters = new SortedDictionary();
16 |
17 | private readonly string _tableName;
18 | private readonly string _whereSql;
19 |
20 | public DapperHelper(string tableName, string whereSql = null)
21 | {
22 | _tableName = tableName;
23 | _whereSql = whereSql;
24 | }
25 |
26 | ///
27 | /// Adds the supplied parameterName to value mapping to a collection
28 | /// of items used in the insert and update values to be modified.
29 | /// This method does not check for existing values
30 | ///
31 | ///
32 | ///
33 | public void Add(string parameterName, object value)
34 | {
35 | if (_parameters.ContainsKey(parameterName))
36 | throw new DuplicateNameException("This field was already declared");
37 |
38 | _parameters.Add(parameterName, value);
39 | }
40 |
41 | ///
42 | /// Method to add variables that will not be affected by insert or update
43 | /// operations but are necessary for use in the where clause
44 | ///
45 | ///
46 | ///
47 | public void AddCondition(string parameterName, object value)
48 | {
49 | if (_parameters.ContainsKey(parameterName) || _conditionalParameters.ContainsKey(parameterName))
50 | throw new DuplicateNameException("This field was already declared");
51 |
52 | _conditionalParameters.Add(parameterName, value);
53 | }
54 |
55 | ///
56 | /// Creates an insert statement for a single record that returns the bigint
57 | /// identity of the record inserted
58 | /// Throws an exception if the collection is empty
59 | ///
60 | public string InsertSql
61 | {
62 | get
63 | {
64 | if (_parameters.Keys.Count == 0)
65 | throw new Exception("Attempted to perform an insert without any input parameters.");
66 |
67 | var fields = string.Join(", ", _parameters.Keys);
68 | var values = string.Join(", @", _parameters.Keys);
69 | return "DECLARE @output table(ID bigint); " +
70 | $"INSERT INTO {_tableName}({fields}) " +
71 | "OUTPUT INSERTED.[ID] " +
72 | "INTO @output " +
73 | $"VALUES(@{values}) " +
74 | "SELECT * FROM @output;";
75 | }
76 | }
77 |
78 | ///
79 | /// Creates an update statement for a single record based on the key value pairs
80 | /// that have been added
81 | /// Throws an exception if the collection is empty
82 | ///
83 | public string UpdateSql
84 | {
85 | get
86 | {
87 | if (string.IsNullOrEmpty(_whereSql))
88 | throw new Exception("Attempted to perform an update without providing a where clause. DapperHelper.UpdateSql");
89 |
90 | if (_parameters.Keys.Count == 0)
91 | throw new Exception("Attempted to perform an update without any input parameters. DapperHelper.UpdateSql");
92 |
93 | var sb = new StringBuilder();
94 | foreach (var parameterName in _parameters.Keys)
95 | {
96 | sb.Append($"{parameterName} = @{parameterName}, ");
97 | }
98 |
99 | return $"UPDATE {_tableName} SET {sb.ToString().Substring(0, sb.Length - 2)} {_whereSql};";
100 | }
101 | }
102 |
103 | ///
104 | /// Generates a DynamicParameters instance based on the key value pairs
105 | /// that have been added
106 | ///
107 | public DynamicParameters Parameters
108 | {
109 | get
110 | {
111 | var parms = new DynamicParameters();
112 | foreach (var parameterName in _parameters.Keys)
113 | {
114 | parms.Add(parameterName, _parameters[parameterName]);
115 | }
116 | foreach (var parameterName in _conditionalParameters.Keys)
117 | {
118 | parms.Add(parameterName, _conditionalParameters[parameterName]);
119 | }
120 | return parms;
121 | }
122 | }
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/DapperHelperDemo/DapperHelperDemo.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp3.1
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/DapperHelperDemo/DatabaseService.cs:
--------------------------------------------------------------------------------
1 | using Dapper;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Data;
5 | using System.Data.SqlClient;
6 | using System.Linq;
7 | using System.Text;
8 |
9 | namespace DapperHelperDemo
10 | {
11 | public class DatabaseService
12 | {
13 | protected string ConnectionString { get; set; }
14 |
15 | public DatabaseService(string connectionString)
16 | {
17 | ConnectionString = connectionString;
18 | }
19 |
20 | public List Query(string sql, object parameters)
21 | {
22 | try
23 | {
24 | using SqlConnection conn = new SqlConnection(ConnectionString);
25 | return conn.Query(sql, parameters).ToList();
26 | }
27 | catch
28 | {
29 | return default;
30 | }
31 | }
32 |
33 | public T QueryFirst(string sql)
34 | {
35 | return QueryFirst(sql, null);
36 | }
37 |
38 | public T QueryFirst(string sql, object parameters)
39 | {
40 | try
41 | {
42 | using SqlConnection conn = new SqlConnection(ConnectionString);
43 | return conn.QueryFirst(sql, parameters);
44 | }
45 | catch(Exception ex)
46 | {
47 | //Log the exception
48 | throw;
49 | }
50 | }
51 |
52 | public T QueryFirstOrDefault(string sql)
53 | {
54 | return QueryFirstOrDefault(sql, null);
55 | }
56 |
57 | public T QueryFirstOrDefault(string sql, object parameters)
58 | {
59 | try
60 | {
61 | using SqlConnection conn = new SqlConnection(ConnectionString);
62 | return conn.QueryFirstOrDefault(sql, parameters);
63 | }
64 | catch
65 | {
66 | //Log the exception
67 | return default;
68 | }
69 | }
70 |
71 | public T QuerySingle(string sql)
72 | {
73 | return QuerySingle(sql, null);
74 | }
75 |
76 | public T QuerySingle(string sql, object parameters)
77 | {
78 | try
79 | {
80 | using SqlConnection conn = new SqlConnection(ConnectionString);
81 | return conn.QuerySingle(sql, parameters);
82 | }
83 | catch(Exception ex)
84 | {
85 | //Log the exception
86 | throw;
87 | }
88 | }
89 |
90 | public T QuerySingleOrDefault(string sql)
91 | {
92 | return QuerySingleOrDefault(sql, null);
93 | }
94 |
95 | public T QuerySingleOrDefault(string sql, object parameters)
96 | {
97 | try
98 | {
99 | using SqlConnection conn = new SqlConnection(ConnectionString);
100 | return conn.QuerySingleOrDefault(sql, parameters);
101 | }
102 | catch (Exception ex)
103 | {
104 | return default;
105 | }
106 | }
107 |
108 | public void Execute(string sql)
109 | {
110 | Execute(sql, null);
111 | }
112 |
113 | public void Execute(string sql, object parameters)
114 | {
115 | using SqlConnection conn = new SqlConnection(ConnectionString);
116 | conn.Execute(sql, parameters);
117 | }
118 |
119 | public T ExecuteScalar(string sql, object parameters)
120 | {
121 | try
122 | {
123 | using SqlConnection conn = new SqlConnection(ConnectionString);
124 | T result = conn.ExecuteScalar(sql, parameters);
125 | return result;
126 | }
127 | catch (Exception ex)
128 | {
129 | return default;
130 | }
131 | }
132 |
133 |
134 | public T ExecuteInsert(DapperHelper helper)
135 | {
136 | return ExecuteScalar(helper.InsertSql, helper.Parameters);
137 | }
138 |
139 | public void ExecuteUpdate(DapperHelper helper)
140 | {
141 | Execute(helper.UpdateSql, helper.Parameters);
142 | }
143 |
144 | public void ExecuteStoredProcedure(string sql)
145 | {
146 | ExecuteStoredProcedure(sql, null);
147 | }
148 |
149 | public void ExecuteStoredProcedure(string sql, object parameters)
150 | {
151 | using (SqlConnection conn = new SqlConnection(ConnectionString))
152 | {
153 | conn.Query(sql, parameters, commandType: CommandType.StoredProcedure);
154 | }
155 | }
156 |
157 | public List ExecuteStoredProcedure(string sql, object parameters)
158 | {
159 | try
160 | {
161 | using (SqlConnection conn = new SqlConnection(ConnectionString))
162 | {
163 | return conn.Query(sql, parameters, commandType: CommandType.StoredProcedure).ToList();
164 | }
165 | }
166 | catch
167 | {
168 | return null;
169 | }
170 | }
171 | }
172 | }
173 |
--------------------------------------------------------------------------------
/DapperHelperDemo/Models/User.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace DapperHelperDemo.Models
6 | {
7 | public class User
8 | {
9 | public int ID { get; set; }
10 | public string FirstName { get; set; }
11 | public string LastName { get; set; }
12 | public DateTime DateOfBirth { get; set; }
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/DapperHelperDemo/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace DapperHelperDemo
4 | {
5 | class Program
6 | {
7 | static void Main(string[] args)
8 | {
9 | DapperHelper helper = new DapperHelper("TableName");
10 | helper.Add("IntValue", 5);
11 | helper.Add("DateTimeValue", DateTime.Now);
12 | helper.Add("StringValue", "This is a string");
13 |
14 | var insertSql = helper.InsertSql;
15 | var parameters = helper.Parameters;
16 |
17 | Console.WriteLine("---------------Insert SQL------------------");
18 | Console.WriteLine(insertSql);
19 | Console.WriteLine("------------Insert Parameters--------------");
20 | foreach (var parameterName in parameters.ParameterNames)
21 | {
22 | var value = parameters.Get(parameterName);
23 | Console.WriteLine(parameterName + ": " + value);
24 | }
25 |
26 | Console.WriteLine("--------------Update SQL-------------------");
27 |
28 | //Remove the WHERE clause to see an exception thrown by DapperHelper.
29 | DapperHelper updateHelper = new DapperHelper("UpdateTableName", "WHERE ID = @id");
30 | updateHelper.AddCondition("id", 5);
31 | updateHelper.Add("DateTimeValue", DateTime.Now);
32 | updateHelper.Add("LongValue", 5827453L);
33 | //Uncomment the below line to see an exception thrown by DapperHelper
34 | //updateHelper.Add("DateTimeValue", DateTime.Now.AddDays(-7));
35 |
36 | var updateSql = updateHelper.UpdateSql;
37 | var updateParameters = updateHelper.Parameters;
38 |
39 | Console.WriteLine(updateSql);
40 |
41 | Console.WriteLine("-----------Update Parameters---------------");
42 |
43 | foreach (var parameterName in updateParameters.ParameterNames)
44 | {
45 | var value = updateParameters.Get(parameterName);
46 | Console.WriteLine(parameterName + ": " + value);
47 | }
48 |
49 |
50 | string connectionString = "Your Connection String";
51 | DatabaseService myDB = new DatabaseService(connectionString);
52 |
53 | //The lines below this point will throw errors at runtime,
54 | //since the connection string above doesn't do anything.
55 | //Comment them out to run the program.
56 |
57 | DapperHelper insertHelper = new DapperHelper("Users"); //"Users" is the SQL table name
58 |
59 | insertHelper.Add("FirstName", "John");
60 | insertHelper.Add("LastName", "Smith");
61 | insertHelper.Add("DateOfBirth", new DateTime(1970, 1, 1));
62 |
63 | myDB = new DatabaseService("ConnectionString");
64 | int userID = myDB.ExecuteInsert(helper);
65 |
66 | updateHelper = new DapperHelper("Users", "WHERE ID = @ID");
67 | updateHelper.AddCondition("ID", 5);
68 | updateHelper.Add("FirstName", "Josephina");
69 | updateHelper.Add("LastName", "Ezekiel-Smith");
70 |
71 | myDB = new DatabaseService("ConnectionString");
72 | myDB.ExecuteUpdate(updateHelper);
73 |
74 | //Comment out the lines above this comment to run the sample
75 |
76 | Console.ReadLine();
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # DapperHelperDemo
2 | This is an example series where I set up a DapperHelper class to generate parameterized SQL statements for INSERTs and UPDATEs. These statements can then be used by Dapper to execute database calls.
3 |
4 | This project is used in the following blog post:
5 |
6 | * [Creating a Dapper Helper C# Class to Generate Parameterized SQL](https://exceptionnotfound.net/creating-a-dapper-helper-csharp-class-to-generate-parameterized-sql-inserts-and-updates/)
7 |
8 | The posts for this series were originally part of my paid newsletter [The Catch Block](https://exceptionnotfound.net/tag/thecatchblock/); you can sign up to get The Catch Block every Wednesday by [clicking here](https://exceptionnotfound.net/membership/) and choosing one of the paid options (yearly or monthly).
9 |
10 | The issues that use this repository are:
11 |
12 | * [The Catch Block #31 - Dapper Helper Beginnings](https://exceptionnotfound.net/the-catch-block-31-dapper-helper-beginnings/)
13 | * [The Catch Block #32 - Dapper Helper UPDATEs](https://exceptionnotfound.net/the-catch-block-32-dapper-helper-updates/)
14 | * [The Catch Block #33 - Dapper Helper Database Service](https://exceptionnotfound.net/the-catch-block-33-dapper-helper-database-service/)
15 |
--------------------------------------------------------------------------------