I've got this helper method SetProperty that sets the property of an object via reflection. Below, is 2 scenarios where I use that method. The first method CreateInstance works just fine, but the second method Insert doesn't work.
In the 2nd method, the property set on the object is lost as soon as the method SetProperty returns. I've debugged it via visual studio. The object has the property set uptill the last closing curly braces. Then as control is returned to the caller Insert, the Property value is lost.
Method that sets properties
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void SetProperty(object destination, string propertyName, object value)
{
var type = destination.GetType();
var property = type.GetProperty(propertyName);
var convertedVal = Convert(value, property.PropertyType);
property.SetValue(destination, convertedVal);
}
The SetProperty method works fine in this method
public static T CreateInstance<T>(SqlDataReader row, IEnumerable<CLASS> columns)
{
var type = typeof(T);
var obj = Activator.CreateInstance(type, true);
foreach (var column in columns)
{
SetProperty(obj, column.BackingPropertyName, column.Name);
}
return (T)obj;
}
The SetProperty method doesn't work in this method
public T Insert<T>(T obj, string table = null)
{
// CODE CHUNK
using (var conn = new SqlConnection(this.ConnectionString))
{
conn.Open();
using (var cmd = new SqlCommand(query.ToString(), conn))
{
// CODE CHUNK
var autoGeneratedValue = cmd.ExecuteScalar();
if (temp.AutoGeneratedColumn != null)
{
ReflectionHelper.SetProperty(
obj,
temp.AutoGeneratedColumn.BackingPropertyName,
autoGeneratedValue
);
}
}
}
return obj;
}
Aucun commentaire:
Enregistrer un commentaire