How to correctly deal with System.Nullable<T> fields of LinqToSql classes?
I've got a table with some nullable double fields. Working with LinqToSQL trying to use the field directly I get
Argument type System.Nullable is not assignable to parameter type double
How do I dea开发者_C百科l with this correctly?
The problem has nothing to do with Linq. It's got to do with conversion between double
and double?
/Nullable<double>
.
Implicit conversion from double?
to double
is not allowed:
double? foo ;
double bar = foo ;
You can reference the double value directly:
double? foo ; double bar = foo.Value ;
This will throw a
NullReferenceException
if theNullable<T>
is null (that is,.HasValue
is false).You can cast it:
double? foo ; double bar = (double) foo ;
Again, you'll get an exception if the
Nullabl<T>
is null.You can use the null coalescing operator to assign a default value if the
Nullable<T>
is null:double? foo ; double bar = foo ?? -1.0 ;
This, natch, avoids the NullReferenceException` problem.
You can use the ternary operator in the same vein as the null coalescing operator:
double? foo ; double bar = ( foo.HasValue ? foo.Value : -2 ) ;
Finally, you can use regular conditional logic to follow an alternative path:
double? foo ; double bar ; if ( foo.HasValue ) { doSomething(foo.Value) ; } else { doSomething() ; }
Those are about the options. Which is correct? I don't know. It depends on your context.
You can use
double value = theObject.TheProperty.GetValueOrDefault();
When you have a Nullable<T>
and you need a value of type T
. This will normalize any null
to the default value of T
, which will be 0.0 for a double. If you want something other than the default, you can work around it another way.
double value = theObject.TheProperty ?? 1d; // where 1 replaces any null
There are two approaches.
Use nullable types such as double?. Your entity class can have a property of double? and your client code will work with the nullable type.
public class Person { public string FirstName { get; set; } public string LastName { get; set; } public double? Age { get; set; } public Person() { } public Person( IDataRecord record ) { FirstName = (string) record["first_name"]; LastName = (string) record["last_name"]; Age = (double?) record["age"]; } }
Write a wrapper around the assignment that chooses a safe default value if NULL is present. I like to use an extension method off the data record class and put a SafeConvert method there.
You can either cast it: double yourVariable = (double)ValueFromDb
or you can just grab the Value of the double?
: double yourVaraible = ValueFromDb.Value
. Either is correct.
精彩评论