Linq-Sql DateTime?
-
Hi guys, Iam trying to update a nullable datetime field in my database using linq-sql. What ever casting method i have tried i keep getting an error: "Specified cast is not valid." Does anyone know how to update a nullable DateTime? field using Linq-Sql? please help me. I have tried:
myVar.dateredeemed = DateTime.Parse("2010-12-03"); //still throws the same error
myVar.dateredeemed = (DateTime?)dateTime; //still throws the same error
myVar.dateredeemed = DateTime.Now; //still throws the same errorI don't really what else i can try because all of the above won't work. Please help me...
-
Hi guys, Iam trying to update a nullable datetime field in my database using linq-sql. What ever casting method i have tried i keep getting an error: "Specified cast is not valid." Does anyone know how to update a nullable DateTime? field using Linq-Sql? please help me. I have tried:
myVar.dateredeemed = DateTime.Parse("2010-12-03"); //still throws the same error
myVar.dateredeemed = (DateTime?)dateTime; //still throws the same error
myVar.dateredeemed = DateTime.Now; //still throws the same errorI don't really what else i can try because all of the above won't work. Please help me...
None of this screams LINQ-to-SQL. Your code should work is
myVar.dateredeemed
is of typeDateTime?
if not, that is the source of your problem. This code works:DateTime? foo;
foo = DateTime.Now;However, you should be wary of this:
myVar.dateredeemed = DateTime.Parse("2010-12-03")
For two reasons:
- If the string really comes from user input, they can enter an incorrect value you need to decide whether this should be null or whether the user *must* enter a valid date. Whichever is the correct strategy, incorrect input will throw an error.
- Can the user enter no date, (i.e. "")? If so you code will not result in null
Finally, I'd say one more thing: If you have luxury of changing the database, avoid nulls (especially in databases) like the plague. You end up with problems similar to the one you have here, potential null reference exceptions, and they make coding SQL harder too. That's not to say don't ever use nulls, but you should think several times before using nullable columns. Personally, I'd use one of the SQL min/max dates in place of null to register "unknown", (a bit like replacing and unknown [null] string with "") but others will disagree. A null date (to represent a date not set yet) is one of the few places I think a null column might be pukka. </rant> - Sorry I didn't mean to go on like this :-).
Sort of a cross between Lawrence of Arabia and Dilbert.[^]
-Or-A Dead ringer for Kate Winslett[^]