I need some clarity for my problem.
I have a method which does this:
public static void SetEntityValue<TEntity>(ref TEntity entityToTransform, PropertyHelper entityProperty)
{
// create type from entity
Type t = entityToTransform.GetType();
// get the property to set
var prop = t.GetProperty(entityProperty.Name);
// set the property value to the one parsed
prop.SetValue(entityToTransform, entityProperty.Value, null);
}
The PropertyHelper just contains two properties, Name and Value.
So, I have a method that takes an Generic Type and then needs to initialise a new one and fill its properties with values, will this method do that:
TEntity ReadIntoEntity<TEntity>(TEntity entity, XElement node)
{
if (!node.HasElements)
throw new IllFormedDocumentException("Entity found but contains no properties");
var xmlProps = node.Elements();
Type t1 = entity.GetType();
// the line which initialises a new TEntity same as string myString = new string();
TEntity newEntity = Activator.CreateInstance<TEntity>();
var props = t1.GetProperties();
var readableProps = props.Select(x => new PropertyHelper(GenericHelper.GetEntityProperty(x), GenericHelper.GetEntityValueAsObject<TEntity>(entity, x)));
List<string> foundAProp = new List<string>();
foreach (var el in xmlProps)
{
// iterate through all xml elements
foreach (var prop in readableProps)
{
// check the prop exists in the xml set
// We found a prop that exists!
if (el.Name.ToString() == prop.Name.ToString())
{
foundAProp.Add(prop.Name.ToString());
GenericHelper.SetEntityValue<TEntity>(ref newEntity, prop);
}
}
}
}
Will this work like Non Generics would do:
MyEntity ReadIntoEntity(XElement node)
{
if (!node.HasElements)
throw new IllFormedDocumentException("Entity found but contains no properties");
var xmlProps = node.Elements();
MyEntity newEntity = new MyEntity();
var props = typeof(MyEntity).GetProperties();
var readableProps = props.Select(x => new PropertyHelper(GenericHelper.GetEntityProperty(x), GenericHelper.GetEntityValueAsObject<TEntity>(entity, x)));
List<string> foundAProp = new List<string>();
foreach (var el in xmlProps)
{
// iterate through all xml elements
foreach (var prop in readableProps)
{
// check the prop exists in the xml set
// We found a prop that exists!
if (el.Name.ToString() == prop.Name.ToString())
{
foundAProp.Add(prop.Name.ToString());
GenericHelper.SetEntityValue<MyEntity>(ref newEntity, prop);
}
}
}
}
So Effectively is:
TEntity newEntity = Activator.CreateInstance<TEntity>();
Equivalent to this:
MyEntity newEntity = new MyEntity();
Thanks
Will that method do the thing? Try it and see.
However:
should be replaced with
after adding the
new()generic constraint for the parameter. This will add compile time checks to ensure that the entity has a valid parameterless constructor. I.e.:And you don’t need
refin your first method, assuming all your entities areclasstypes.