我使用AutoMapper在我的域模型和视图模型之间进行映射。我的网站主机只支持中等信任,因此AutoMapper不起作用。对于像AutoMapper这样可以在中等信任下运行的优秀映射器,是否还有其他建议?
我无法在主机上访问IIS。
答案 0 :(得分:3)
如果您的模型使用具有相同名称的属性,则可以开发这样的简单映射器:
public static class Mapper {
/// <summary>
/// Copy all not null properties values of object source in object target if the properties are present.
/// Use this method to copy only simple type properties, not collections.
/// </summary>
/// <param name="source">source object</param>
/// <param name="target">target object</param>
private static void SimpleCopy(object source, object target)
{
foreach (PropertyInfo pi in source.GetType().GetProperties())
{
object propValue = pi.GetGetMethod().Invoke(source, null);
if (propValue != null)
{
try
{
PropertyInfo pit = GetTargetProperty(pi.Name, target);
if (pit != null) pit.GetSetMethod().Invoke(target, new object[] { propValue });
}
catch (Exception) { /* do nothing */ }
}
}
}
private static PropertyInfo GetTargetProperty(string name, object target)
{
foreach (PropertyInfo pi in target.GetType().GetProperties())
{
if (pi.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase)) return pi;
}
return null;
}
}