0
 dataSet = clsDb.MailData("SELECT * FROM CM_Mail cm WHERE cm.[ActualTime] < '" + DateTimeOffset.UtcNow + "' ", CommandType.Text);
        DataTable datatablepending = (from ds in dataSet.Tables[0].AsEnumerable() where ds.Field<string>("Status") == MailStatus.Pending.ToString() select ds).CopyToDataTable();
        DataTable datatableInprogress = (from ds in dataSet.Tables[0].AsEnumerable() where ds.Field<string>("Status") == MailStatus.Inprogress.ToString() select ds).CopyToDataTable();

        if (datatablepending.Rows.Count != 0)
        {
            for (int i = 0; i < datatablepending.Rows.Count; i++)
            {

                dataSet = clsDb.MailData("UPDATE CM_Mail SET [Status] = '" + updateStatus + "',LastProccessedTime = '" + DateTimeOffset.UtcNow.ToString() + "' WHERE Id='" + datatablepending.Rows[i]["Id"].ToString() + "'", CommandType.Text);
            }

        }
        if (datatableInprogress.Rows.Count != 0)
        {
            for (int i = 0; i < datatableInprogress.Rows.Count; i++)
            {
                dataSet = clsDb.MailData("UPDATE CM_Mail SET [Status] = '" + updateStatus + "',SentTime = '" + DateTimeOffset.UtcNow + "',LastProccessedTime = '" + DateTimeOffset.UtcNow.ToString() + "' WHERE Id='" + datatableInprogress.Rows[i]["Id"].ToString() + "'", CommandType.Text);
            }



        }

当我尝试这样做时,datatableInprogress可能一直没有任何行。在运行时,我得到一个异常说“没有数据源”。为什么?我应该怎么做才能解决这个问题?

4

1 回答 1

0

如果您的条件没有行,只需克隆 DataTable 结构:

var pendingRows = 
  dataSet.Tables[0].AsEnumerable()
         .Where(r => r.Field<string>("Status") == MailStatus.Pending.ToString());

DataTable datatablepending = pendingRows.Any() ? pendingRows.CopyToDataTable() :
                                                 dataSet.Tables[0].Clone();

顺便说一句,为什么需要 DataTable?可以获得身份证!

var pendingIds = 
     from r in dataSet.Tables[0].AsEnumerable()
     where r.Field<string>("Status") == MailStatus.Pending.ToString()
     select r.Field<int>("Id");

抱歉,我不知道你为什么要在循环中分配 dataSet,但这里是重现你的代码:

string updateStringFormat = 
 "UPDATE CM_Mail SET [Status] = '{0}',LastProccessedTime = '{1}' WHERE Id='{2}'";

foreach(var id in pendingIds)
{
    var commandText = String.Format(updateStringFormat, updateStatus, DateTimeOffset.UtcNow, id);
    dataSet = clsDb.MailData(commandText, CommandType.Text);
}
于 2013-03-15T07:32:52.297 回答