Initializing object to handle null query results

后端 未结 4 1505
北海茫月
北海茫月 2021-01-15 02:56

I have an object model like this:

public class MyObject{
  public int Prop1{get;set;}
  public int Prop2{get;set;}
}

I use this object in a

相关标签:
4条回答
  • 2021-01-15 03:20

    Is your database type nullable?

    If so, you will need to define in your class:

    public int? Prop1 { get; set; }
    

    or convert your database type to an int using Convert.ToInt32(databseField) in your cast.

    0 讨论(0)
  • 2021-01-15 03:22

    Two places you could fix:

     public int? Prop1{get;set;}
    

    or

     select new MyObject()
                {
                  Prop1 = // check for null here and put default value.
    
    0 讨论(0)
  • 2021-01-15 03:24

    Why not use Nullable<int> then?

    public class MyObject{
      public int? Prop1{get;set;}
      public int? Prop2{get;set;}
    }
    

    int? is a shorthand of Nullable<int>. That means, now Prop1 and Prop2 both can be null.

    Or if you want zero, instead of null, then do this in the LINQ :

    select new MyObject() { Prop1  = p1 ?? 0,  Prop2 = p2 ?? 0 }
    
    0 讨论(0)
  • 2021-01-15 03:31

    You could do this way:

    select new MyObject()
                {
                  Prop1 = prop1 ?? 0;
                  Prop2 = prop2 ?? 0;
                };
    

    But it is better to use nullables.

    0 讨论(0)
提交回复
热议问题