ASP.NET与Sql Server数据库的空数据的交互

数据库中的字段:(1) ArticleId int型 外键 可空 (2) recommendedReason nvarchar型 可空
实体类有相应的ArticleId和recommendedReason属性
思想:数据库中的null值与实体类中的可空整型,string型相互转换操作;
1.插入时:
SqlParameter[] paras = new SqlParameter[] {
    new SqlParameter("@articleId",recommend.ArticleId==null?System.Data.SqlTypes.SqlString.Null:recommend.ArticleId.ToString()),
    new SqlParameter("@recommendedReason", string.IsNullOrEmpty(recommend.RecommendedReason)?System.Data.SqlTypes.SqlString.Null:recommend.RecommendedReason.ToString())
};
2.更新时:
SqlParameter[] paras = new SqlParameter[] {
    new SqlParameter("@articleId",recommend.ArticleId==null?System.Data.SqlTypes.SqlString.Null:recommend.ArticleId.ToString()),
    new SqlParameter("@recommendedReason",string.IsNullOrEmpty(recommend.RecommendedReason)?System.Data.SqlTypes.SqlString.Null:recommend.RecommendedReason.ToString()),
    new SqlParameter("@Id",recommend.Id.ToString())
};
3.获取(实体类)时:
recommend.ArticleId = dt.Rows[0]["ArticleId"]==DBNull.Value?(int?)null:Convert.ToInt32(dt.Rows[0]["ArticleId"].ToString());
recommend.RecommendedReason = dt.Rows[0]["RecommendedReason"]==DBNull.Value?null:dt.Rows[0]["RecommendedReason"].ToString();
注:recommend.RecommendedReason = dt.Rows[0]["RecommendedReason"]==DBNull.Value?null:dt.Rows[0]["RecommendedReason"].ToString();
recommend.ArticleId = dt.Rows[0]["ArticleId"]==DBNull.Value?(int?)null:Convert.ToInt32(dt.Rows[0]["ArticleId"].ToString());(定义类型int?可空)
DateTime类型可用(DateTime?)null给属性赋值.

你可能感兴趣的:(SQL Server,asp.net)