Linq on datatable没有数据源异常

时间:2013-03-15 07:06:49

标签: linq datatable

 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可能没有任何行。在运行时,我得到一个例外,说“没有数据源”。为什么?我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

如果您的条件没有行,则只需clone DataTable structure

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();

BTW为什么你需要DataTable?你可以得到ids!

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);
}