Reputation: 2913
I have a generic function to create objects from a DataRow
using reflection. I'm using this function to import tables from an Access database:
private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
{
T item = new T();
foreach (var prop in properties)
{
try
{
if (prop.PropertyType.IsEnum)
prop.SetValue(item, row[prop.Name], null); // what to do??
else
prop.SetValue(item, row[prop.Name], null);
}
catch (Exception ex)
{
System.Diagnostics.Debug.Assert(false, string.Format("failed to assign {0} a value of {1}", prop.Name, row[prop.Name]));
}
}
return item;
}
The problem I'm running into is when the property type is an enum
. I've tried using Enum.Parse
, but that hasn't been successful (I can't get anything to compile).
Is there any way to convert the object represented by row[prop.Name]
to the correct enum
using my function? Or do I need to write a special conversion function specific for the enum
s I've defined.
Edit: I am getting
"the type or namespace prop could not be found. Are you missing an assembly directive or reference" compile error for the following:
var val = (prop.PropertyType)Enum.Parse(typeof(prop.PropertyType), row[prop.Name].ToString());
Upvotes: 3
Views: 3601
Reputation: 218
My class is like this
public enum Status
{
Active,
Deactive
}
public class Sample
{
public long Id{ get; set; }
public string Name{ get; set; }
public Status UserStatus{ get; set; }
}
In database i stored Status="Active" as string. I used your solution, but got following error
System.ArgumentException: 'The value passed in must be an enum base or an underlying type for an enum, such as an Int32. Parameter name: value'
Upvotes: 0
Reputation: 16393
The reason for the type or namespace prop could not be found
exception you were getting is because you cannot cast to a type in this way (prop.PropertyType)Enum.Parse(typeof(prop.PropertyType)
- you can only do that where you know the type at compile time - (SomeEnum)Enum.Parse(typeof(SomeEnum)
.
The correct way to do it is to get the enum value before setting the property value:
prop.SetValue(item, Enum.ToObject(prop.PropertyType, row[prop.Name]), null);
Upvotes: 4