Retrieve value from Model attributes raise "Object does not match target type" in C#

59 Views Asked by At

I am trying to retrieve attribute information from the Identity User Model. Data in the User model either came from a database or API and here is the Model Properties and values.

From the controller, I am retrieving data by sending userName from the database. sending the value to GetAttribute(typeof(Users)); to retrieve attribute information.

    public async Task<ActionResult<Users>> get_attibutes(string userName)
    {
        var users = await _userManager.FindByNameAsync(userName);
        
        GetAttribute(typeof(Users));
        
        return Ok(); 
    } 

and the GetAttribute() function is:

        public static void GetAttribute(Type t)
        {
            PropertyInfo[] propertiesInfo = t.GetProperties();
            foreach (PropertyInfo propertyInfo in propertiesInfo)
            {
                if (!string.IsNullOrEmpty(propertyInfo.Name)) 
                {
                    string propery_name = propertyInfo.Name;
                    string property_type = propertyInfo.PropertyType.Name;

                    string property_value = propertyInfo.GetValue(t);     // Object does not match target type

                    Console.WriteLine($"Attribute Name: { propery_name } , type: { property_type }, value: { property_value }");
                }

            }
        } 

from the above code attribute name & type are perfectly found but getting error Object does not match the target type when retrieving the value of the attribute string property_value = propertyInfo.GetValue(t); here.

What I am trying to achieve is to get each property name, property value, and property type. here is the Final Result.

Property_Name : FirstName
Property_value: Tazbir
Property_type : string

I am trying to get a proper solution but it's just taking time. Thanks in advance.

1

There are 1 best solutions below

0
Suryateja KONDLA On BEST ANSWER

you're trying to get the value of a property on the type t rather than an instance of that type

public static void GetAttribute(object obj)
{
    Type t = obj.GetType();
    PropertyInfo[] propertiesInfo = t.GetProperties();
    foreach (PropertyInfo propertyInfo in propertiesInfo)
    {
        if (!string.IsNullOrEmpty(propertyInfo.Name)) 
        {
            string propery_name = propertyInfo.Name;
            string property_type = propertyInfo.PropertyType.Name;

            // Here, pass the instance `obj` to GetValue, not the type `t`.
            object property_value = propertyInfo.GetValue(obj, null); 

            Console.WriteLine($"Attribute Name: { propery_name }, type: { property_type }, value: { property_value }");
        }
    }
}