Update Entity Framework Objects using HashTable in ASP.Net

Last Reply 3 months ago By abhi619

Posted 3 months ago

I am updating data EF table item by hashtable dynamically but when I do the save changes, my data is not updating in the DB table.  

UserMaster EntityObj = context.UserMasters.FirstOrDefault(user => user.DataID == DataID);
Type description = typeof(UserMaster);
foreach (string htKey in ht.Keys)
{
    PropertyInfo property = description.GetProperty(htKey);
    object htValue = ht[htKey];
    object result = AppHelper.ConvertValueType(htValue, property.PropertyType.Name);
    property.SetValue(EntityObj, result);
}
context.SaveChanges();

Here ht is hastable. What is wrong with this code or is there anyway to dynamically bind data to the db model object and update data in database?

Hashtable ht = new Hashtable();
ht.Add( "username", "Abhi" );
ht.Add( "Role", "Admin" );
ht.Add( "FirstName", "Abhi" );
ht.Add( "email", "ab@cd.com" );

 

Posted 3 months ago Modified on 3 months ago

It is working now. Don't know the reason why it wasn't working before but code started working.

        public bool UpdateUserByHash(UserMaster EntityObj, Hashtable ht, string UserType)
        {
            Type description = typeof(UserMaster);
            EntityObj = context.UserMasters.FirstOrDefault(user => user.DataID == EntityObj.DataID);
            foreach (string htKey in ht.Keys)
            {
                PropertyInfo property = description.GetProperty(htKey);
                object htValue = ht[htKey];
                object result = AppHelper.ConvertValueType(htValue, property.PropertyType.Name);
                object ColValue = property.GetValue(EntityObj);
                if (ColValue == null)
                {
                    property.SetValue(EntityObj, result);
                }
                else
                if (!ColValue.Equals(result))
                {
                    property.SetValue(EntityObj, result);
                }
            }
            context.SaveChanges();
            return true;
        }