❔ .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
I typically go with the below to get rid of those errors where you will be initialising it.
(I don't know if this is standard/accepted practice. Just inputting what I do 🙂 )
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.
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.aaaah ok cool
I wonder if null! is a shorthand for default()
Thanks for that
I think it's the suppression syntax for properties. Though, I may be wrong 😁
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"ah right so it's just for the compiler
Conceptually, how do we feel adding these to what are basically POCOs?
It's the workaround for versions older than 7
So it's fine to use it
cool
thanks for the responses!
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
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.