I want to update database object with model object values how do i get the value of the property inside modelObject that is a List?
Imagine an object like this
public class Worker{
public string Id { get; set; }
public bool GoodPerson { get; set; }
public bool Wise { get; set; }
public List<string> Formation { get; set; }
}
I dont know how to get the values from Formation property, so how can i reflect the edited values in Formation property to my dataBaseObject, CAN YOU PLEASE HELP ME?
how can i reflect these changes using reflection?
public static void UpdateObjectFrom(this object modelObject, object dataBaseObject, string[] excludedProperties = null)
{
//WHAT IF THE modelObject is now List<string> ?????, how do i pass the values of modelObject for the dataBaseObject List<string> object
Type modelObjectType = modelObject.GetType();
Type dataBaseObjectType = dataBaseObject.GetType();
PropertyInfo[] modelProperties = modelObjectType.GetProperties();
PropertyInfo[] dataBaseProperties = dataBaseObjectType.GetProperties();
if (excludedProperties != null)
{
dataBaseProperties = dataBaseProperties.Where(x => !excludedProperties.Contains(x.Name)).ToArray();
}
foreach (PropertyInfo dataBasePropInfo in dataBaseProperties)
{
if (HasSimpleType(dataBasePropInfo.PropertyType) || dataBasePropInfo.PropertyType.IsGenericType && dataBasePropInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
PropertyInfo modelPropInfo = modelObjectType.GetProperty(dataBasePropInfo.Name);
dataBasePropInfo.SetValue(dataBaseObject, modelPropInfo.GetValue(modelObject));
}
else if (dataBasePropInfo.PropertyType.IsGenericType)
{
UpdateObjectFrom(dataBasePropInfo.GetValue(dataBaseObject, null), modelObjectType.GetProperty(dataBasePropInfo.Name).GetValue(modelObject, null));
}
else if (dataBasePropInfo.PropertyType.IsClass && !dataBasePropInfo.PropertyType.FullName.StartsWith("System."))
{
UpdateObjectFrom(dataBasePropInfo.GetValue(dataBaseObject, null), modelObjectType.GetProperty(dataBasePropInfo.Name).GetValue(modelObject, null));
}
}
}
private static bool HasSimpleType(Type tipo)
{
return tipo.IsPrimitive || tipo == typeof(string) || tipo.IsEnum || tipo == typeof(Decimal) || tipo == typeof(DateTime);
}