Initializing an object to process results with a null query

I have an object model:

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

I use this object in a linq to sql query, for example:

 var MyQuery = from.... where.... select new MyObject() { Prop1 = ... Prop2 = ... }; 

The problem is that sometimes Prop1 turns out to be empty in the request, and I get an error because Prop1 is null.

I add this to the class:

 public class MyObject{ ... public void Init() { this.Prop1 = 0; this.Prop2 = 0; } 

How to bind Init with the "just created object" event?

And, does null solve the problem by initializing object 0 in the best way to do this?

Thanks for your suggestions.

edit: I am using Prop1 in the user interface and I cannot display null, must be 0.

+2
source share
4 answers

You can do this:

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

But it is better to use nullables.

+4
source

Why not use a Nullable<int> then?

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

int? is a shorthand for Nullable<int> . This means that now Prop1 and Prop2 both can be null .

Or if you want null, not null, then do it in LINQ:

 select new MyObject() { Prop1 = p1 ?? 0, Prop2 = p2 ?? 0 } 
+2
source

Is your database type null?

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

 public int? Prop1 { get; set; } 

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

+2
source

Two places you could fix:

  public int? Prop1{get;set;} 

or

  select new MyObject() { Prop1 = // check for null here and put default value. 
+2
source

Source: https://habr.com/ru/post/1486352/


All Articles