1

我在 CopyToDataTable 方法中收到此错误。

ArgumentNullException 值不能为空。参数名称:来源

按照 - http://msdn.microsoft.com/en-us/library/bb669096%28v=vs.110%29.aspx的程序

public DataTable GetAllRecords()
  {
    try
     {
       DataTable dt = new DataTable();
       IEnumerable<DataRow> query = ((from p in MedianDB.tblCountries
                  select p).OrderBy(p => p.CountryName)) as IEnumerable<DataRow>;
       query.CopyToDataTable<DataRow>(dt,LoadOption.PreserveChanges);
       return dt;                
     }
   catch (Exception ex)
     {
       throw ex;
     }
  }

使用 .Net Framework 4.0,实体数据模型

4

1 回答 1

1

Okay, so this is pretty straight forward. You're getting an ArgumentNullException and that's documented as such:

The source IEnumerable sequence is null or the destination DataTable is null.

We know that dt isn't null so this means that the issue is you're query is null. So to fix it you should be able to leverage the AsEnumerable extension:

IEnumerable<DataRow> query = (from p in MedianDB.tblCountries
                              select p)
                             .OrderBy(p => p.CountryName)
                             .AsEnumerable();
query.CopyToDataTable<DataRow>(dt,LoadOption.PreserveChanges);

You can't just cast the result you were getting as an IEnumerable<DataRow>, you need to make it an IEnumerable<DataRow>. This code, as IEnumerable<DataRow>, was giving you a null.


And just an FYI, this catch is actually worse than just letting it throw because you're losing the stack trace in the process:

catch (Exception ex)
{
    throw ex;
}

Just get rid of the try/catch all together if you're not really going to handle it.

于 2013-10-31T12:29:23.210 回答