Claudio Ludovico Panetta February 2016

C# and Reflection don't work twice in a row

I've a problem and I can't figured it out how to solve it.

I've a class for fetching data from a Database, in this class I've a method for a simple select * this method is called

List<T> All<T>(string tableName)

and you have to specify which resource you want to fetch, for example

All<User>("users")

And, aside from the classic SQL Reader and SQL Command, the core of the method is this

public override List<T> All<T>(string resource) 
    {
        List<T> result = new List<T>();
        using (MySqlConnection sqlConnection = new MySqlConnection(connectionString))
        {
            sqlConnection.Open();
            try
            {
                string query = "SELECT * FROM " + resource + " WHERE 1=1";
                using (MySqlCommand sqlCommand = new MySqlCommand(query, sqlConnection))
                {
                    lock (locker)
                    {
                        MySqlDataReader reader = sqlCommand.ExecuteReader();
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                T model = Activator.CreateInstance<T>();
                                Dictionary<string, object> _properties = new Dictionary<string, object>();
                                for (int i = 0; i < reader.FieldCount; i++)
                                {
                                    string property = reader.GetName(i);
                                    object value = reader.GetValue(i);
                                    _properties.Add(property, value);
                                }
                                var type = model.GetType();
                                var method = type.GetMethod("SetProperties");
                                var invo        

Answers


CodingGorilla February 2016

The result of:

var invoked = method.Invoke(model, new object[] { _properties });

Is the return value from your SetProperties method, not whether the method was invoked as your question indicates. Your SetProperties method is telling you that it was unable to do its work, debug that and you will find your answer.

Post Status

Asked in February 2016
Viewed 3,407 times
Voted 12
Answered 1 times

Search




Leave an answer