Thursday, November 26, 2015

Generate SQL update queries in C# for models with empty data


Here's the scenario:
You get a payload using a model that contains only a subset of the fields populated. The remaining fields contain null\default values, however, while writing an update query, you cannot set the default values in your statement since you'd like to ignore them.

So, I wrote a small helper method that allows you to handle this case.
You can then build your update statement using the following method. I'm using the Dapper library as ORM.

There are risks using this method such as SQL Injection, etc. so you're better of using Prepared Statements 99% of the time. However, if you'd like to write ad-hoc SQL queries, this should suffice.

No comments:

Post a Comment