我有一个需要将视图模型与数据库模型同步的 MVC3 应用程序。我发现自己编写了太多代码来在不同对象之间来回复制属性。我避免了这种情况,我可以简单地对数据模型进行子类化,但在其他时候,我发现这太限制了。
我在 Object 上开发了一些扩展方法来支持具有相似名称的属性的浅层克隆,并且效果很好。但是,我想知道是否有更有效的方法来完成同样的事情。所以我想这是要求同行评审和改进此代码的选项。
更新:我发现明确处理相关表更好。对 IsVirtual 的测试将防止在克隆期间无意中影响关系。请参阅更新的 CloneMatching 方法。其他人明确说明要更新或排除哪些属性。
public static class CustomExtensions
{
public static T CloneMatching<T, S>(this T target, S source)
where T : class
where S : class
{
if (source == null)
{
return target;
}
Type sourceType = typeof(S);
Type targetType = typeof(T);
BindingFlags flags = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = sourceType.GetProperties();
foreach (PropertyInfo sPI in properties)
{
PropertyInfo tPI = targetType.GetProperty(sPI.Name,flags);
if (tPI != null && tPI.PropertyType.IsAssignableFrom(sPI.PropertyType) && !tPI.PropertyType.IsVirtual)
{
tPI.SetValue(target, sPI.GetValue(source, null), null);
}
}
return target;
}
public static T CloneProperties<T, S>(this T target, S source, string[] propertyNames)
where T : class
where S : class
{
if (source == null)
{
return target;
}
Type sourceType = typeof(S);
Type targetType = typeof(T);
BindingFlags flags = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = sourceType.GetProperties();
foreach (PropertyInfo sPI in properties)
{
if (propertyNames.Contains(sPI.Name))
{
PropertyInfo tPI = targetType.GetProperty(sPI.Name, flags);
if (tPI != null && tPI.PropertyType.IsAssignableFrom(sPI.PropertyType))
{
tPI.SetValue(target, sPI.GetValue(source, null), null);
}
}
}
return target;
}
public static T CloneExcept<T, S>(this T target, S source, string[] propertyNames)
where T : class
where S : class
{
if (source == null)
{
return target;
}
Type sourceType = typeof(S);
Type targetType = typeof(T);
BindingFlags flags = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = sourceType.GetProperties();
foreach (PropertyInfo sPI in properties)
{
if (!propertyNames.Contains(sPI.Name))
{
PropertyInfo tPI = targetType.GetProperty(sPI.Name, flags);
if (tPI != null && tPI.PropertyType.IsAssignableFrom(sPI.PropertyType))
{
tPI.SetValue(target, sPI.GetValue(source, null), null);
}
}
}
return target;
}
}
这是我如何使用它将视图模型映射到数据模型的示例。
DataSession.Quote.CloneProperties(viewModel,
new[] {"PaymentType","CardHolder","CardHolderZip","CardNumber","CardExp","CVC",
"AccountHolder","AccountHolderZip","ABA","Account",
"AccuracyAgreement","PrivacyTermsAgreement","ElectronicSignatureAgreement"});