I have a class type object, such as:
Private Class Car
Public Property Make As String
Public Property Model As String
Public Property Used As Boolean?
Public Property Mileage As Integer?
Public Property DateSold As Date?
End Class
I'm parsing a query string that's posted to my page that may or may not have key/value pairs for the above properties. For example, it may just be:
?Make=Toyota
I have a table in SQL Server based on the Public Properties you see above, and I'm allowing NULLS on all columns. (My real data has more fields, so this is for explanation purposes)
CREATE PROCEDURE InsertCar
@Make varchar(25),
@Model varchar(25),
etc.
I'm not setting default values in the parameters in the stored procedure above. I want to know of a cleaner way to do this from code.
For example:
The data is posted to my page... I use httputility to parse it, and I can build a new object, such as:
Dim record As New Car
record.Make = Data("make")
record.Model = Data("model")
record.Used = Data("used")
record.Mileage = Data("mileage")
record.DateSold = Data("datesold")
Afterwards, I build some parameters for my stored procedure, but here's where I think I can improve:
Dim pars As New List(Of SqlParameter)
pars.Add(New SqlParameter("@Make", If(record.Make = Nothing, DBNull.Value, record.Make))
and so on...
So you can see my ternary operators for building the parameters. Is there a cleaner way, perhaps using default values or when the class is being put together to make this cleaner?
This is more of a precision and best practice question I think. Should I be assigning DBNull.Value to the public properties? Or is how I'm doing it sufficient? Is there a cleaner way to map nullable properties?
My values from the query string are parsed into a NameValueCollection, so is there an easier way to just iterate over the ones that exist, and if not exist in the class, automatically build the parameter with DBNull.Value?
I hope my question makes sense. With a lot of data it just seems ugly with all the if/then DBNull.value, etc. I feel like I could be saving myself a step somewhere along the way. The class object is helpful for organization and is utilized in other parts of the code, or else I'd probably just build the parameters and be done with it.