初始化对象来处理空查询结果 [英] Initializing object to handle null query results
问题描述
我有这样一个对象模型:
公共类为MyObject {
公众诠释为prop1 {获取;集;}
公众诠释Prop2 {获取;设置;}
}
我使用这个对象的LINQ to SQL的查询是这样的:
VAR更改为MyQuery =从......
其中。 ...
选择新MyObject来()
{
为prop1 = ...
Prop2 = ...
};
的问题是,有时为prop1原来在查询空的,我得到一个错误,因为为prop1为空
我加入这类:
公开类为MyObject {
...
公共无效的init()
{
this.Prop1 = 0;
this.Prop2 = 0;
}
如何链接初始化事件刚刚创建的对象?
和,将通过初始化对象为0,这样做也无妨最好的方式解决一个空的问题?
< 。p>感谢您的建议
编辑:我在UI使用为prop1,我不能显示为空,必须为0
您可以做这样的:
选择新为MyObject()
{
为prop1 =为prop1? 0;
Prop2 = prop2? 0;
};
但它是更好地使用nullables。
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 linq to sql query like this:
var MyQuery = from....
where....
select new MyObject()
{
Prop1 = ...
Prop2 = ...
};
The problem is that sometimes Prop1 turns out empty in the query and I get an error because Prop1 is null.
I'm adding this to the class:
public class MyObject{
...
public void Init()
{
this.Prop1 = 0;
this.Prop2 = 0;
}
How do I link Init to the event "object just got created"?
And, is solving the problem of a null by initializing the object to 0 the best way to do it anyway?
Thanks for your suggestions.
edit: I'm using Prop1 in the UI and I can't display null, must be 0.
You could do this way:
select new MyObject()
{
Prop1 = prop1 ?? 0;
Prop2 = prop2 ?? 0;
};
But it is better to use nullables.
这篇关于初始化对象来处理空查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!