我有一个asp.net文本表单,其中包含许多可选的十进制字段。我想有选择地更新数据库,但不为没有数据的字段插入“0”(保持空状态)。
通常,我会创建多个函数,每个函数都有不同的签名来处理这个问题。但是,我通过Web服务插入数据,该服务不允许具有相同名称的函数具有多个签名。我可以想办法解决这个问题,但没有一个“务实”。
谢谢!
答案 0 :(得分:2)
Nullable Types用于同一目的。它们代表了值类型,可能没有数据。可以使用这些类型的HasValue属性检查值的存在。
用于读取字段的伪代码:
decimal? dValue; // default value is null
if(decimalValueExists)
{
dValue = <value read from text file>
}
当你说多个方法时 - 我假设这些是重载方法,以便能够添加可选字段(所以n个可选字段意味着更多方法)
您可以通过编写单个方法来避免编写这些方法。假设您有一个必填字段和一个可选字段:
public class MyFields
{
decimal req1;
decimal? opt1; // optional field 1
}
然后定义要使用它的Web服务方法:
[WebMethod]
void MyWSMethod(MyFields myFields)
{/* code here will ultimately call InsertMyFields */}
void InsertMyFields(MyFields myFields)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create the command and set its properties.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "AddMyFields";
command.CommandType = CommandType.StoredProcedure;
// Add the required input parameter
SqlParameter parameter1 = new SqlParameter();
parameter1.ParameterName = "@ReqField1";
parameter1.SqlDbType = SqlDbType.NVarChar;
parameter1.Direction = ParameterDirection.Input;
parameter1.Value = myFields.req1;
// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter1);
// Add the optional parameter and set its properties.
SqlParameter parameter2 = new SqlParameter();
parameter2.ParameterName = "@OptField1";
parameter2.SqlDbType = SqlDbType.NVarChar;
parameter2.Direction = ParameterDirection.Input;
parameter2.Value = myFields.opt1 ?? DBNull.Value; //null coalescing operator
// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter2);
//.. rest of the code
}
}
如果可空类型有值,Null Coalescing Operator将设置值,否则它将设置您指定的另一个值(在我们的例子中为DBNull.Value)。
答案 1 :(得分:2)
您可以将参数定义为可为空的小数。可以为null的值类型的C#语法,如下所示:
decimal? rebateAmountOrWhatever;
然后,您可以在变量中存储空值,并将该变量与null进行比较。
new SqlParameter("@RebateAmount",
rebateAmountOrWhatever == null ? (object)DBNull.Value : (object)rebateAmountOrWhatever)
使用??也很有趣像这样的运算符:
new SqlParameter("@RebateAmount",
(object)rebateAmountOrWhatever ?? (object)DBNull.Value)
声明变量的等效方法是使用Nullable&lt;&gt;通用类型如下:
Nullable<decimal> currentIraBalance = null;
答案 2 :(得分:1)
您可以使用DBNull class在Web服务代码上表示空值。
虽然您仍然需要使用代理值(例如,0或-1),然后只评估该值以将其转换为DBNull
对象。