How to deal with the System.Nullable <T> fields of the LinqToSql classes?

I have a table with multiple fields with a null value. Working with LinqToSQL, trying to use the field directly, I get

The argument type System.Nullable is not assigned to the parameter type double

How can I handle this?

+5
source share
4 answers

The problem has nothing to do with Linq. This is due to the conversion between doubleand double?/ Nullable<double>.

Implicit conversion from double?to is doublenot allowed:

double? foo ;
double  bar = foo ;
  • You can directly refer to a double value:

    double? foo ;
    double  bar = foo.Value ;
    

    This will cause NullReferenceExceptionif Nullable<T>null (i.e. .HasValue, false).

  • :

    double? foo ;
    double  bar = (double) foo ;
    

    , , Nullabl<T> null.

  • null coalescing , Nullable<T> null:

    double? foo ;
    double  bar = foo ?? -1.0 ;
    

    , natch, NullReferenceException`.

  • , :

    double? foo ;
    double  bar = ( foo.HasValue ? foo.Value : -2 ) ;
    
  • , , :

    double? foo ;
    double  bar ;
    
    if ( foo.HasValue )
    {
      doSomething(foo.Value) ;
    }
    else
    {
      doSomething() ;
    }
    

. ? . .

+19

double value = theObject.TheProperty.GetValueOrDefault();

Nullable<T>, T. null T, 0.0 double. - , .

double value = theObject.TheProperty ?? 1d; // where 1 replaces any null
+7

.

  • , double?. double? NULL.

    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"];
        }
    }
    
  • , , NULL. SafeConvert.

+2

: double yourVariable = (double)ValueFromDb double?: double yourVaraible = ValueFromDb.Value. .

-1

All Articles