Search code examples
c#xmlentity-frameworkdatatabledata-conversion

Error Adding DataTable Rows to Entity Framework Invoices Table


I am trying to populate an Entity Framework table from a DataTable that is populated with values from an XML file. However, I encounter an error when attempting to add these rows to my Entity Framework model.

Here’s the relevant part of my code:

// Populating DataTable from XML
DataRow row = table.NewRow();
row["InvoiceNumber"] = xmlData.ChildNodes[2].ChildNodes[0].ChildNodes[2].ChildNodes[0].InnerText;
row["InvoiceIssueDate"] = Convert.ToDateTime(xmlData.ChildNodes[2].ChildNodes[0].ChildNodes[2].ChildNodes[1].InnerText);
row["InvoiceDeliveryDate"] = Convert.ToDateTime(xmlData.ChildNodes[2].ChildNodes[0].ChildNodes[2].ChildNodes[2].InnerText);

// Adding to Entity Framework table
Invoices invoices = new Invoices();
invoices.InvoiceNumber = table.Rows[0].ToString(); // This is likely incorrect
invoices.InvoiceIssueDate = table.Rows[1]; // This should be a DateTime
invoices.InvoiceDeliveryDate = table.Rows[2]; // This should be a DateTime

Error Details:

When I try to run this code, I receive the following error message:

Cannot convert System.Data.Datarow to System.DateTime

Questions:

  • How should I properly assign values from the DataTable to the Invoices object?
  • What is the correct way to convert DataRow values to the appropriate types for the Invoices properties?

Additional Information:

  • The InvoiceNumber is a string.

  • InvoiceIssueDate and InvoiceDeliveryDate are DateTime types in the Invoices entity.


Solution

  • try this.

    invoices.InvoiceIssueDate = Convert.ToDateTime(table.Rows[1]);
    invoices.InvoiceDeliveryDate = Convert.ToDateTime(table.Rows[2]);