【发布时间】:2019-10-03 18:22:12
【问题描述】:
我试图找到一种方法将发布到 Web 服务的对象保存到由实体管理的数据库中。
我不想手动复制每个属性,而是想要一种无需编写太多代码即可复制所有属性的方法。
例如:objectFromClient.Copy(objectToDatabase);
这将节省我复制每个属性的多行代码。我喜欢这个问题中给出的建议代码。
Apply properties values from one object to another of the same type automatically?
但是这对 Entity 跟踪的对象不起作用,因为不能在 Entity 中修改 Key 属性。
我做了一些修改以跳过那些标记为 EntityKey 的列。
我不确定这是否是正确的方法。有人可以评论吗?
using System;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Reflection;
/// <summary>
/// A static class for reflection type functions
/// </summary>
public static class Reflection
{
/// <summary>
/// Extension for 'Object' that copies the properties to a destination object.
/// </summary>
/// <param name="source">The source.</param>
/// <param name="destination">The destination.</param>
public static void CopyProperties(this object source, object destination)
{
// If any this null throw an exception
if (source == null || destination == null)
throw new Exception("Source or/and Destination Objects are null");
// Getting the Types of the objects
Type typeDest = destination.GetType();
Type typeSrc = source.GetType();
// Collect all the valid properties to map
var results = from srcProp in typeSrc.GetProperties()
let targetProperty = typeDest.GetProperty(srcProp.Name)
where srcProp.CanRead
&& targetProperty != null
&& (targetProperty.GetSetMethod(true) != null && !targetProperty.GetSetMethod(true).IsPrivate)
&& (targetProperty.GetSetMethod().Attributes & MethodAttributes.Static) == 0
&& targetProperty.PropertyType.IsAssignableFrom(srcProp.PropertyType)
&& targetProperty.GetCustomAttributes(false).Where(a => a is EdmScalarPropertyAttribute && ((EdmScalarPropertyAttribute)a).EntityKeyProperty).Count() == 0
&& srcProp.Name != "EntityKey"
select new { sourceProperty = srcProp, targetProperty = targetProperty };
//map the properties
foreach (var props in results)
{
//System.Diagnostics.Debug.WriteLine(props.targetProperty.Name);
props.targetProperty.SetValue(destination, props.sourceProperty.GetValue(source, null), null);
}
}
}
【问题讨论】:
-
如果此代码有您知道的问题,您可能希望在此处发布它们。如果此代码有效,并且您正在寻找评论,那么您最好在Code Review 处获得更好的结果。