C# 验证数据库中的int数据
下面的代码说明了类模型的使用:C# 验证数据库中的int数据,c#,validation,asp.net-mvc-4,C#,Validation,Asp.net Mvc 4,下面的代码说明了类模型的使用:Student public class Student: IAbstract { public int StudentID { get; set; } public string FirstName { get; set; } public int Age { get; set; } //Some methods } 这是来自StudentController public ActionResult Index() { v
Student
public class Student: IAbstract
{
public int StudentID { get; set; }
public string FirstName { get; set; }
public int Age { get; set; }
//Some methods
}
这是来自StudentController
public ActionResult Index()
{
var model = new List<Student>();
var objStudent = new Student();
var cmd = new SqlBuilder();
cmd.CommandText = "SELECT StudentID, FirstName, Age FROM Students";
var data = objStudent.Select(cmd);
foreach (DataRow item in data.Tables[0].Rows)
{
model.Add(new Student
{
StudentID = Convert.ToInt32(item["StudentID"]),
FirstName = item["FirstName"].ToString(),
Age = item.IsNull("Age")?0:Convert.ToInt32(item["Age"]) //Here
});
}
return View("Index", model);
}
将
Age
设置为可为空的整数:
public int? Age { get; set; }
那么默认值将为nothing,而不是0
然后,您的解析逻辑可能如下所示:
Age = item.IsNull("Age") ? null : (int?)Convert.ToInt32(item["Age"]) //Here
将
Age
设置为可为空的整数:
public int? Age { get; set; }
那么默认值将为nothing,而不是0
然后,您的解析逻辑可能如下所示:
Age = item.IsNull("Age") ? null : (int?)Convert.ToInt32(item["Age"]) //Here
我考虑过了,但我得到了以下错误
error 3无法确定条件表达式的类型,因为在“”和“int”之间没有隐式转换
哇,是的,您需要将右侧强制转换为int?
,以使条件操作有效。查看我的编辑。我考虑过了,但我得到了以下错误error 3无法确定条件表达式的类型,因为“”和“int”之间没有隐式转换whoops,是的,您需要将右侧强制转换为int?
,以使条件操作有效。请参阅我的编辑。