WCF Error: Cannot serialize the DataTable. DataTable name is not set

Error:

Cannot serialize the DataTable. DataTable name is not set.

Solution:

The above error is thrown from a WCF Service which tries to return a DataTable.

In my case I have a WCF Service which returns a DataTable and I am trying to consume the WCF Service from a WPF Applicatioin and I get the above error.

Did some research on the Error, and got it resolved. Looks like the DataTable needs to have a Table name without which the WCF Service is not able to serialize it.

So I had to assign a Table name to the TableName Property of the DataTable I was returning back from the WCF Service and that seemed to solve the problem.

Here is what I had to change in the code. I am showing both the old and new code to see the change.

Old Code

public DataTable GetDataByTableName(string tableName)

        {

 

            DataTable dt = new DataTable();

            string connString = "Data Source=localhost;Initial Catalog=DataBaseName;Integrated Security=True;Asynchronous Processing=True";

            string sqlQuery = "Select top 10 * from TableName";

 

           

            using (SqlConnection conn = new SqlConnection(connString))

            {

                using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))

                {

                    using (SqlDataAdapter daGetDataByTableName = new SqlDataAdapter(cmd))

                    {

                        daGetDataByTableName.Fill(dt);

                    }

                }

            }

 

            return dt;

        }

New Code

public DataTable GetDataByTableName(string tableName)

        {

 

            DataTable dt = new DataTable();

            string connString = "Data Source=localhost;Initial Catalog=DataBaseName;Integrated Security=True;Asynchronous Processing=True";

            string sqlQuery = "Select top 10 * from TableName";

 

            dt.TableName = "MyTableName";  //Added this Line

 

            using (SqlConnection conn = new SqlConnection(connString))

            {

                using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))

                {

                    using (SqlDataAdapter daGetDataByTableName = new SqlDataAdapter(cmd))

                    {

                        daGetDataByTableName.Fill(dt);

                    }

                }

            }

 

            return dt;

        }

Hope this helpful to some one.

 

Robert

Tags: