Skip to content

Instantly share code, notes, and snippets.

@aaronolds
Last active September 22, 2015 21:19
Show Gist options
  • Save aaronolds/0fcfd5dc6b2a2e9ca608 to your computer and use it in GitHub Desktop.
Save aaronolds/0fcfd5dc6b2a2e9ca608 to your computer and use it in GitHub Desktop.
Convert and set properties dynamically on Entity Framework Models
public static void SetValue<T>(T obj, string fieldName, object value)
{
var type = typeof(T);
// Get our property via reflection so that we can invoke methods against property
var prop = type.GetProperty(fieldName, BindingFlags.Public | BindingFlags.Instance);
if (prop == null || !prop.CanWrite) return;
// Gets what the data type is of our property (Foreign Key Property)
var propertyType = prop.PropertyType;
prop.SetValue(obj, ChangeType(value, propertyType), null);
}
public static object ChangeType(object value, Type conversionType)
{
// Note: This if block was taken from Convert.ChangeType as is, and is needed here since we're
// checking properties on conversionType below.
if (conversionType == null)
{
throw new ArgumentNullException("conversionType");
} // end if
// If it's not a nullable type, just pass through the parameters to Convert.ChangeType
if (!conversionType.IsGenericType || conversionType.GetGenericTypeDefinition() != typeof (Nullable<>)) return Convert.ChangeType(value, conversionType);
// It's a nullable type, so instead of calling Convert.ChangeType directly which would throw a
// InvalidCastException determine what the underlying type is
// If it's null, it won't convert to the underlying type, but that's fine since nulls don't really
// have a type--so just return null
// Note: We only do this check if we're converting to a nullable type, since doing it outside
// would diverge from Convert.ChangeType's behavior, which throws an InvalidCastException if
// value is null and conversionType is a value type.
if (value == null)
{
return null;
}
// It's a nullable type, and not null, so that means it can be converted to its underlying type,
// so overwrite the passed-in conversion type with this underlying type
var nullableConverter = new NullableConverter(conversionType);
conversionType = nullableConverter.UnderlyingType;
// Now that we've guaranteed conversionType is something Convert.ChangeType can handle (i.e. not a
// nullable type), pass the call on to Convert.ChangeType
return Convert.ChangeType(value, conversionType);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment