I am writing a console app that will hit a REST api, deserialize the JSON to a C# model and then persist that model using ADO into a db table.
First issue is that during the first run of the app we found that one of the JSON properties exceeded the column definition of nvarchar(300)
. We increased that column to nvarchar(4000)
, but I have no idea if any of the other dozen string properties might exceed the default of 300 I gave them.
FYI, the SQL error I got was:
String or binary data would be truncated.
The data for table-valued parameter "@Items" doesn't conform to the table type of the parameter. SQL Server error is: 8152, state: 10
The statement has been terminated.
...which makes sense if I was passing in a string with length 500 to an nvarchar(300)
So my desire: during deserialization or model creation in C# I would like to truncate the string properties/fields and give them a max length before I hit my persistence code so that I can ensure with 100% confidence that my fields will never exceed the nvarchar lengths and will never trigger the 'truncation error'.
I tried using System.ComponentModel.DataAnnotations and [MaxLength(4000)]
, but that seemed only for MVC and input validation during form POSTing.
I thought about making backing fields with custom setters, but that means having twice the lines of code in each of my entities. I have 9 entities and each probably has 2 dozen strings that I want to configure/truncate.
So question: is there any fancy way to truncate strings using some sort of NewtonSoft data annotation or a C# data annotation? Also, is there a magic way to avoid having a bazillion back fields? Or should I just make a custom string class and inherit from String that has a max length property?