将NULL转换为0的问题 [英] Problems with converting NULL to 0
本文介绍了将NULL转换为0的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好。
请帮我解决以下问题。我有一个DataRow r,填充了我数据库中的数据。现在我要填写一个MVC模型
Hi there.
Help me please with the following problem. I have a DataRow r, filled with data from my database. Now I want to fill an MVC model
public class Customer
{
private int id;
private string name;
private string region;
private int phone;
public int Id {get, set}
public string Name {get, set}
public string Region {get, set}
public int Phone {get, set}
}
如下所示
as shown below
var c = new Customer {
Id = Convert.ToInt32(r[0]),
Name = r[1].ToString(),
Region = r[2].ToString(),
Phone = Convert.ToInt32(r[3])
}
问题是r [3]对应于可选数据,如果我的数据库中存在NULL,则会发生转换错误。在r [3]为NULL的情况下,我可以使用什么来使Phone变为0?
The problem is that r[3] corresponds to optional data, and if there is NULL in my database, an error with Convert occurs. What can I use to make Phone to be just 0 in the case when r[3] is NULL ?
推荐答案
将它作为值存储在类中的问题0是如果你将它保存回数据库,你可能会用0覆盖NULL值。
更好的选择是使用Nullable< int>数据类型,允许表示缺失值或电话号码。
此外,电话号码最好存储为字符串。它们比一个数字更复杂。有些有重要的前导0,有些可能是国际的,有些可能比整数可以代表的大。
The problem with storing it in your class as value of 0 is that if you save it back to the database, you will possibly overwrite the NULL value with 0.
A better option is to use the Nullable<int> data type, which allows representation of a missing value, or the phone number.
Also, phone numbers are better stored as strings. They are more complex than just a number. Some have important leading 0's, some may be international, some may be bigger than what an integer can represent.
你应该可以使用Convert.IsDBNull
You should be able to useConvert.IsDBNull
var c = new Customer {
Id = Convert.ToInt32(r[0]),
Name = r[1].ToString(),
Region = r[2].ToString(),
Phone = Convert.IsDBNull(r[3]) ? 0 : Convert.ToInt32(r[3])
}
这篇关于将NULL转换为0的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文