views:

6339

answers:

4

When I retrieve a record using LINQ that has a DateTime field only the ToString() is available.

Where are all the other DateTime methods?

I have to Convert.ToDateTime the DateTime? that the Field returns?

What is the difference between (DateTime) and (DateTime?)

A: 

The namespace collision aside, I know that SQL's datetime has a different epoch (and therefore a different range of valid dates) than C# datetime.

Try to send a new DateTime() to a stored procedure and see what I mean.

Ryan
+13  A: 

If by DateTime? you mean a Nullable<DateTime>, then you can get the DateTime value via the DateTime?.Value property.

Mark Cidade
...or by casting the DateTime? into a DateTime. In either case, you should check if it is null first or you will get an exception.
Lucas
Thanks! I know it was almost a year ago but your answer just kept me from posting a new question.
Swingley
+7  A: 

In SQL, DateTimes are allowed to be null. In C# DateTimes cannot be null. You can read a little bit about nullable value types. Since value typed variables cannot be null, a generic class was created to handle this situation. It is called Nullable<> and it is commonly written with a question mark after the type.

In order to use these values you will want to check the .HasValue property. It is a boolean that knows whether there is a value in the object or it is null. Once you have checked that the .HasValue property is true, you can safely use the .Value property. The .Value property will be of type DateTime.

Brendan Enrick
The HasValue was quite helpful for me working with checking possibly NULL integer values in a LINQ query like so: c.Field(Of Integer?)("SecondaryID").HasValue
atconway
+1  A: 

In SQL, you have the DateTime field set to Allow Null. Then in LINQ, when you're going to access the field, .NET doesn't know if the field is really a date or not, which is why you have to Convert.ToDateTime() before any date methods become available to you.

If the field will always contain a date, set the database column to NOT NULL and you should be fine.

Otto