Ankush Madankar
Ankush Madankar

Reputation: 3834

Update command updating wrong values

I am using C#, MS Access as database.I create class with properties of same as Table in database and trying to update database by this class properties using Reflection and class key value use in where condition for updatation purpose. Following is method which handle this:

    public void UpdateDBByObject(object objClass, string key, object keyValue, string tableName = null)
    {
        string _updateQuery = string.Empty;

        Type objType = objClass.GetType();
        List<PropertyInfo> propertyList = new List<PropertyInfo>(objType.GetProperties());

        Dictionary<string, object> _props = new Dictionary<string, object>();

        _updateQuery += "update " + (string.IsNullOrEmpty(tableName) ? objType.ToString().Split('.').LastOrDefault().TrimEnd('s') : tableName) + " set";

        foreach (var prop in propertyList)
        {
            string _name = prop.Name;
            if (_name == key) continue;

            _updateQuery += " [" + _name + "] = ?,";

            _props.Add(_name, prop.GetValue(objClass, null));
        }
        _updateQuery = _updateQuery.TrimEnd(',');
        _updateQuery += " where " + key + " = ?";

        OleDbCommand cmd = new OleDbCommand();
        OleDbConnection conn;
        cmd.CommandType = CommandType.Text;

        cmd.CommandText = _updateQuery;

        foreach (string value in _props.Keys)
        {
            object _addValue;
            cmd.Parameters.AddWithValue("@" + value, _props.TryGetValue(value, out _addValue));
        }

        cmd.Parameters.AddWithValue("@" + key, keyValue);

        conn = GetOpenConnection();
        cmd.Connection = conn;
        cmd.ExecuteNonQuery();
        CloseConnection(conn);
    }

this method working but updating wrong values in database, i.e. for string value it update "-1" value, for DateTime it update min DateTime value. Please find out error and let me know.

Upvotes: 0

Views: 93

Answers (2)

user3138460
user3138460

Reputation:

TryGetValue(value,out object) will out bool value hence for every time it will bool value.

 object outValue;
 cmd.Parameters.AddWithValue("@" + value, _props.TryGetValue(value, out outValue));

Upvotes: 1

Ankush Madankar
Ankush Madankar

Reputation: 3834

I was adding bool value as paramenter in following line of code:

cmd.Parameters.AddWithValue("@" + value, _props.TryGetValue(value, out _addValue));

After changing this code works fine.

Upvotes: 0

Related Questions