什么是最佳实践,用于处理空int/char从SQL数据库?
-
11-07-2019 - |
题
我有一个数据库,举行一个用户可选择的配置文件。在本轮廓我strings,char(M或F)和int.
我跑进一个问题,在这里我试着把性的用户进入的财产,我的个人资料的对象,并将应用程序的崩溃,因为它不知道如何处理退回的空值。
我已经试过了铸造的数据为适当的类型
char sex = (char)dt.Rows[0]["Sex"];
这也没解决我的问题。然后我试图改变类型可空的和可空的,并得到转换问题的所有相同。我目前的解决方案,我能够找到如下:
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();
}
}
其他提示
可空类型设计只是为了这个目的!使用'为char?代替 '(字符?)'
class Foo {
char? sex;
}
Foo object;
object.sex = dt.Rows[0]["Sex"] as char?;
一个体面的讨论,这是在 最有效的方式来检查DBNull然后分配给可变?.
时DT的ADO.Net 2数据表?你不能做这样的事情:
if(dt.Rows[0].IsSexNull()) {} else {}
?另外,假设你可以控制你的数据库,岂不更有意义使用了一下,而不是一个字符串?
怎么样:
internal static T CastTo<T>(object value)
{
return value != DBNull.Value ? (T)value : default(T);
}
,然后用它喜欢:
return new EquipmentDetails(
CastTo<int>(reader["ID"]),
CastTo<int>(reader["CategoryID"]),
CastTo<string>(reader["Description"]));
等...
我会做到这一点非常像你一样。我将写一个函数为它:
东西做:
object.sex = handle(dt.Rows[0]["Sex"]);
和手柄你做的== DBNull.Value检查。
不隶属于 StackOverflow