初始化对象以处理空查询结果
我有一个像这样的对象模型:
public class MyObject{ public int Prop1{get;set;} public int Prop2{get;set;} }
我在linq to sql查询中使用此对象,如下所示:
var MyQuery = from.... where.... select new MyObject() { Prop1 = ... Prop2 = ... };
问题是,有时Prop1在查询中变为空,我得到一个错误,因为Prop1为null。
我正在向课堂添加:
public class MyObject{ ... public void Init() { this.Prop1 = 0; this.Prop2 = 0; }
如何将Init链接到事件“刚刚创建的对象”?
并且,通过将对象初始化为0来解决null的问题无论如何最好的方法是什么?
谢谢你的建议。
编辑:我在UI中使用Prop1,我无法显示null,必须为0。
你可以这样做:
select new MyObject() { Prop1 = prop1 ?? 0; Prop2 = prop2 ?? 0; };
但最好使用nullables。
你可以解决的两个地方:
public int? Prop1{get;set;}
要么
select new MyObject() { Prop1 = // check for null here and put default value.
为什么不使用Nullable
呢?
public class MyObject{ public int? Prop1{get;set;} public int? Prop2{get;set;} }
int?
是Nullable
的简写。 这意味着,现在Prop1
和Prop2
都可以为null
。
或者如果你想要零,而不是null,那么在LINQ中执行此操作:
select new MyObject() { Prop1 = p1 ?? 0, Prop2 = p2 ?? 0 }
您的数据库类型是否可为空?
如果是这样,您需要在class级中定义:
public int? Prop1 { get; set; }
或者使用转换中的Convert.ToInt32(databseField)
将数据库类型转换为int
。