Home > Software engineering >  I am creating a generic data reader function for get data from database but i am facing a issue
I am creating a generic data reader function for get data from database but i am facing a issue

Time:06-21

I am creating a generic data reader function for get data from database but i am facing a issue. "Unable to cast object of type 'System.String' to type 'MyBooks.Data.Model.Book"

Kindly Help me

 public List<T> GetDataMethod<T>(SqlCommand cmd)
    {
        cmd.Connection = getcon();
        SqlDataReader reader = cmd.ExecuteReader();
        List<T> records = new List<T>();
        while (reader.Read())
        {
            object[] tempRow = new object[reader.FieldCount];
            for (int i = 0; i < reader.FieldCount; i  )
            {
                tempRow[i] = reader[i];
            }
            //Error showing > can not convert from object[] to T
            records.Add(tempRow);
        }
        return records;
    }

CodePudding user response:

You can use a generic type. You'll need to return a list of objects then create code to map between the list of objects to the type you need.

public List<object[]> GetDataMethod(SqlCommand cmd)
    {
        cmd.Connection = getcon();
        SqlDataReader reader = cmd.ExecuteReader();
        List<object[]> records = new List<object[]>();
        while (reader.Read())
        {
            object[] tempRow = new object[reader.FieldCount];
            for (int i = 0; i < reader.FieldCount; i  )
            {
                tempRow[i] = reader[i];
            }
            //Error showing > can not convert from object[] to T
            records.Add(tempRow);
        }
        return records;
    }

CodePudding user response:

tempRow is a DataRow. And T is of type MyBooks.Data.Model.Book. What you want to do is map the values to the properties of Book. E.g. if Book has a property of "Title" and you know, that the title is in the DataRow at index 0:

var newBook = new Book();
newBook.Title = tempRow[0];
records.Add(newBook);
  • Related