一、在Foreach之前要判断是否为空。
常常从数据库里取出来表就直接用了,很少记得判断是否有值。不严谨的说。
专业人员写的是酱滴。。。
1 DataLayer.PMSecDataSet.PMSECRequestDataTable requestDataTable = adapter.up_PMSec_PMSECRequestSelectByMasterIDs(masterIds); 2 3 if (requestDataTable != null && requestDataTable.Count > 0) 4 { 5 ... 6 }
二、当数据库中允许为空。
话说,上次已经说过的啦。。。但是这次更加明确,要用Nullable<int>.
1 Nullable<int> intNull = null; 2 DataLayer.PMSecDataSet.PMSECRequestDataTable requestDataTable = adapter.up_PMSec_PMSECRequestSelectByMasterIDs(masterIds); 3 4 if (requestDataTable != null && requestDataTable.Count > 0) 5 { 6 7 foreach (DataLayer.PMSecDataSet.PMSECRequestRow dr in requestDataTable.Rows) 8 { 9 PMSecRequestInfo requestInfo = new PMSecRequestInfo(); 10 requestInfo.RequestMasterID = dr.RequestMasterID; 11 requestInfo.EmployeeID = dr.EmployeeID; 12 Employee requestEmployee = new Employee(dr.EmployeeID); 13 requestInfo.DisplayName = requestEmployee.DisplayName; 14 requestInfo.StatusType = dr.StatusType; 15 requestInfo.CompanyID = dr.CompanyID; 16 requestInfo.WorkStoreID = dr.WorkStoreID; 17 requestInfo.JobCode = dr.JobCode; 18 requestInfo.RequestedSecurityLevel = dr.IsRequestedSecurityLevelNull() ? intNull : dr.RequestedSecurityLevel; 19 requestInfo.IsSecurityAdmin = dr.IsSecurityAdmin; 20 requestInfo.CreatedBy = dr.CreatedBy; 21 requestInfo.CreatedOn = dr.CreatedOn; 22 23 requestInfoList.Add(requestInfo); 24 } 25 }
string类无需此处理。
三、操作数据库时
当含有update等更改数据库内容的语句存在时,如果下面操作仍与数据库有关,考虑到程序的扩展性,可能出现上述语句删除了某些数据,下面语句出现异常,或者产生错误结果,等等。
譬如下面两段代码,前者是我的做法,后者为Cynthia的做法,一见高下啊啊啊。我写的好像是舒克和贝塔里那只笨猫,喵,~~~~(>_<)~~~~ 。
1 public void ApporveOrDeclineRequest(string masterIds, string statusType, int loginEid) 2 { 3 PMSECRequestPendingTaskTableAdapter adapter = new PMSECRequestPendingTaskTableAdapter(); 4 adapter.up_PMSec_PMSECRequestUpdate(masterIds, statusType, loginEid); 5 6 // Send Email 7 PandaRG.Common.OrgChart.Employee logInEmployee = new Common.OrgChart.Employee(loginEid); 8 9 if (statusType == RequestStatusType.APPROVED.ToString()) 10 { 11 EmailSendHelper.SentEmailbyEmailType(RequestStatusType.APPROVED, GetRequestInfoListByRequestMasterIds(masterIds), logInEmployee); 12 13 } 14 else if(statusType==RequestStatusType.DECLINED.ToString()) 15 { 16 EmailSendHelper.SentEmailbyEmailType(RequestStatusType.DECLINED, GetRequestInfoListByRequestMasterIds(masterIds), logInEmployee); 17 } 18 }
1 public void UpdatePMSECRequest(string masterIds, RequestStatusType statusType, Employee loginEmployee) 2 { 3 PMSECRequestPendingTaskTableAdapter adapter = new PMSECRequestPendingTaskTableAdapter(); 4 5 List<PMSecRequestInfo> requestInfoList = GetRequestInfoListByRequestMasterIds(masterIds); 6 adapter.up_PMSec_PMSECRequestUpdate(masterIds, statusType.ToString(), loginEmployee.EmployeeId); 7 EmailSendHelper.SentEmailbyEmailType(statusType, requestInfoList, loginEmployee); 8 }
四、 λ 表达式
好复杂的说,不老明白的,计入λ 番外篇吧。
( ^_^ )/~~