添加可选参数
本文关键字:参数 添加 | 更新日期: 2023-09-27 18:36:39
我想在下面的代码中为objTest.TestNumber提供可选的参数值。我的代码如下:-
public class TestInfo
{
public int Id { get; set; }
public string TestNumber { get; set; }
}
public string TestUpdate(TestInfo objTest)
{
int retVal = 0;
try
{
dataContext = new AccretiveAPIContext(GetConnection(locationId));
retVal = dataContext.Database.ExecuteSqlCommand(
"EXEC usp_TestUpdate @ID, @TestNumber",
new SqlParameter("@ID", objTest.Id),
new SqlParameter("@TestNumber", objTest.TestNumber),
);
}
catch (Exception)
{
throw;
}
return retVal.ToString();
}
请告诉我需要进行的更改才能使"@TestNumber",objTest.TestNumber 作为可选参数。我想将其默认值设置为零("0")。
请帮忙。
甚至更容易 -
retVal = dataContext.Database.ExecuteSqlCommand(
"EXEC usp_TestUpdate @ID, @TestNumber",
new SqlParameter("@ID", objTest.Id),
new SqlParameter("@TestNumber", string.IsNullOrEmpty(objTest.TestNumber) ? "0" : objTest.TestNumber),
按如下方式更改 TestInfo 类:
public class TestInfo
{
private string _testNumber;
public int Id { get; set; }
public string TestNumber
{
get
{
if (string.IsNullOrEmpty(_testNumber))
{
_testNumber = "0";
}
return _testNumber;
}
set { _testNumber = value; }
}
}
你也可以修改你的方法,说这样的话:
var testNumber = string.IsNullOrEmpty(objTest.TestNumber) ? "0" : obj.TestNumber;