0

I am developing a application to read records from a MySql Data Base. I want to read all records and parte then to a list .

This is my code:

 var command = DatabaseConnection.MySql_Connection.CreateCommand();
 command.CommandText = @"SELECT * FROM Words";
 var reader = await command.ExecuteReaderAsync();
 _records = (List<Words>)reader.OfType<Words>();

But the error is

System.InvalidCastException: 'Unable to cast object of type 'd__611[MySql02Net.Words]' to type 'System.Collections.Generic.List1[MySql02Net.Words]'.'

Someone can help me? Regards

1
  • 1
    AFAIK there's nothing out of the box for this,you need to use an object mapper such as Dapper, then you could use something like DatabaseConnection.MySql_Connection.Query<Words>("SELECT * FROM Words"); Commented Jan 31, 2023 at 9:41

1 Answer 1

2

OfType returns an IEnumerable, not a list. Something like this ought to work:

var reader = await command.ExecuteReaderAsync();
_records = reader.OfType<Words>().ToList();
Sign up to request clarification or add additional context in comments.

2 Comments

OfType won't do any custom conversions though, so the resulting list will be empty since MySqlDataReader doesn't enumerate Words it enumerates DbDataRecord. The following would yield results _records = _reader.OfType<DbDataRecord>();. You still need some kind of data mapper or conversion to convert from a reader to a custom class
@GarethD: Thanks. I thought it would do some simple mapping. Since it doesn't Dapper would definitely be my choice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.