c# - Setting nested properties via an Expression -
i have following object:
public class contactimport { public long id {get;set;} public contact contact {get;set;} public company company {get;set;} public address address {get;set;} }
i want able set properties on the nested objects dynamically based on expression passed in (expression<func<t, dynamic>>
).
to have following method, works fine setting properties on top level object (such id) fails when trying set on nested objects (such contact.firstname)
public static void setpropertyvalue<t, tprop>(this t target, expression<func<t, tprop>> member, tprop value) { var selectorexpr = (memberexpression)(member.body unaryexpression ? ((unaryexpression)member.body).operand : member.body); if (selectorexpr != null) { var property = selectorexpr.member propertyinfo; if (property != null) { property.setvalue(target, value); } } }
it looks it's trying set property on top level object can't. take possible i'm unsure how achieve have.
the setpropertyvalue
method invoke this:
public class importcheck<t> { public int id { get; set; } public string name { get; set; } public type type { get; set; } public bool required { get; set; } public int? minlength { get; set; } public int? maxlength { get; set; } public string value { get; set; } public expression<func<t, dynamic>> associatedproperty { get; set; } } t pt = (t)activator.createinstance(typeof(t)); foreach (var m in mapping) { pt.setpropertyvalue(m.associatedproperty, convert.changetype(m.value, nullable.getunderlyingtype(m.type) ?? m.type)); }
in above example t
contactimport
, m.associatedproperty
expression , mapping
list<importcheck<contactimport>>
.
update
my issue seems boil down fact expression being passed setpropertyvalue
has return type of dynamic
. if set int
, property on nested object int
works. problem have need explicitly set result of expression match type of target property. leaves me issue in need list of importcheck
s possibility of each expression<func<t,dynamic>>
having different return type.
Comments
Post a Comment