我有一个数据库,其中包含用户的可选配置文件。在配置文件中,我有字符串、字符(用于 M 或 F)和整数。
我遇到了一个问题,我试图将用户的性别放入我的 Profile 对象的属性中,但应用程序崩溃了,因为它不知道如何处理返回的空值。
我已尝试将数据转换为适当的类型
char sex = (char)dt.Rows[0]["Sex"];
这并没有解决我的问题。然后我尝试将类型更改为 Nullable 和 Nullable 并得到相同的转换问题。我目前能够找到的解决方案如下:
object.sex = null;
if(dt.Rows[0]["Sex"] != DBNull.Value)
object.sex = (char)dt.Rows[0]["Sex"];
object.WorkExt = null;
if(dt.Rows[0]["WorkExt"] != DBNull.Value)
object.WorkExt = (int)dt.Rows[0]["WorkExt"];
有没有更简单或更好的方法来做到这一点?还是我走在正确的轨道上?
最佳答案
rotard 的回答(使用 Is<ColumnName>Null()
)仅适用于类型化数据集。
对于无类型数据集,您必须使用以下代码中的模式之一。如果此代码不是确定的,请告诉我,我会对其进行编辑,直到确定为止。这是一个极其常见的问题,实际上应该只有一个正确答案。
using System.
using System.Data;
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("test", typeof (char));
dt.Columns["test"].AllowDBNull = true;
DataRow dr = dt.Rows.Add();
char? test;
try
{
test = (char?)dr["test"];
}
catch (InvalidCastException)
{
Console.WriteLine("Simply casting to a nullable type doesn't work.");
}
test = dr.Field<char?>("test");
if (test == null)
{
Console.WriteLine("The Field extension method in .NET 3.5 converts System.DBNull to null.");
}
test = (dr["test"] is DBNull) ? null : (char?) dr["test"];
if (test == null)
{
Console.WriteLine("Before .NET 3.5, you have to check the type of the column's value.");
}
test = (dr["test"] == DBNull.Value) ? null : (char?) dr["test"];
if (test == null)
{
Console.WriteLine("Comparing the field's value to DBNull.Value is very marginally faster, but takes a bit more code.");
}
// now let's put the data back
try
{
dr["test"] = test;
}
catch (ArgumentException)
{
Console.WriteLine("You can't set nullable columns to null.");
}
dr.SetField("test", test);
if (dr["test"] is DBNull)
{
Console.WriteLine("Again, in .NET 3.5 extension methods make this relatively easy.");
}
dr["test"] = (object)test ?? DBNull.Value;
if (dr["test"] is DBNull)
{
Console.WriteLine("Before .NET 3.5, you can use the null coalescing operator, but note the awful cast required.");
}
Console.ReadLine();
}
}
关于c# - 从 SQL 数据库处理 null int/char 的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/318567/