❔ .NET 6.0 - Nullable Strings with Dapper Model Classes

Hey everyone. I have a .NET 6.0 project that uses Dapper to communicate to a database and I have a class which contains properties that map to a table. One of my properties is a string and I'm getting the nullable warning (which goes away when I add the nullable?), however in the table the column is a non nullable string. What would be the recommended approach for this property? I could easily add the nullable? but then it means we can pass null in and out where that is not the case. On the opposite side, I could add a blank string assignment ('public string MyProperty { get; set; } = string.Empty;' ), however this is meant to be a dumb, model class and adding an assignment feels incorrect.
11 Replies
Amos
Amos2y ago
I typically go with the below to get rid of those errors where you will be initialising it.
public string Property { get; set; } = null!;
public string Property { get; set; } = null!;
(I don't know if this is standard/accepted practice. Just inputting what I do 🙂 )
kingofarrows
kingofarrowsOP2y ago
Ah thanks for the response! Although the column that this represents is a non-nullable string, so I don't know if it's appropriate to keep this as a nullable string.
Amos
Amos2y ago
Sorry, correction on my original. If will never be null then I use = null!;, if it can be null then I use the ? after the type. It's contextual to your implementation though. I think ? is nicer.
kingofarrows
kingofarrowsOP2y ago
aaaah ok cool I wonder if null! is a shorthand for default() Thanks for that
Amos
Amos2y ago
I think it's the suppression syntax for properties. Though, I may be wrong 😁
Angius
Angius2y ago
In .NET 7 you can have required properties If you decide to not upgrade, = null!; would be probably the best way. null! just shuts up the compiler, "set it to null, but trust me bro, it will never actually be null"
kingofarrows
kingofarrowsOP2y ago
ah right so it's just for the compiler Conceptually, how do we feel adding these to what are basically POCOs?
Angius
Angius2y ago
It's the workaround for versions older than 7 So it's fine to use it
kingofarrows
kingofarrowsOP2y ago
cool thanks for the responses!
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server