❔ .NET 6.0 - Nullable Strings with Dapper Model Classes

KKingOfArrows11/27/2022
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.
AAyymoss11/27/2022
I typically go with the below to get rid of those errors where you will be initialising it.
public string Property { get; set; } = null!;

(I don't know if this is standard/accepted practice. Just inputting what I do 🙂 )
KKingOfArrows11/27/2022
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.
AAyymoss11/27/2022
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.
AAyymoss11/27/2022
It's contextual to your implementation though. I think ? is nicer.
KKingOfArrows11/27/2022
aaaah ok cool
KKingOfArrows11/27/2022
I wonder if null! is a shorthand for default()
KKingOfArrows11/27/2022
Thanks for that
AAyymoss11/28/2022
I think it's the suppression syntax for properties. Though, I may be wrong 😁
AAngius11/28/2022
In .NET 7 you can have required properties
AAngius11/28/2022
If you decide to not upgrade, = null!; would be probably the best way.
AAngius11/28/2022
null! just shuts up the compiler, "set it to null, but trust me bro, it will never actually be null"
KKingOfArrows11/28/2022
ah right so it's just for the compiler
KKingOfArrows11/28/2022
Conceptually, how do we feel adding these to what are basically POCOs?
AAngius11/28/2022
It's the workaround for versions older than 7
AAngius11/28/2022
So it's fine to use it
KKingOfArrows11/28/2022
cool
KKingOfArrows11/28/2022
thanks for the responses!
Ttebeco11/28/2022
yeah I would try the requried way
Ttebeco11/28/2022
it ideally would moves the problem to the actual place / responsible of the value possibly being null => the plkace you instanciate, instead of the declaration
AAccord11/29/2022
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.