【问题标题】:How to copy properties from one .net object to another如何将属性从一个.net 对象复制到另一个
【发布时间】: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 处获得更好的结果。

标签: c# .net


【解决方案1】:

我想要一种方法来复制所有属性,而不是手动复制每个属性。

您是否尝试过使用 AutoMapper?检查这个link

AutoMapper 是一个简单的小库,旨在解决看似复杂的问题 - 摆脱将一个对象映射到另一个对象的代码。

我在任何地方都使用它,摆脱你必须编写的代码非常有用:)

【讨论】:

  • 它可能满足我的需要。谢谢你指点我那里。但是这个简单的扩展方法看起来更干净。
【解决方案2】:

此函数会将属性从一个对象复制到另一个对象。

private static Target CopyProperties<Source, Target>(Source source, Target target)
    {
        foreach (var sProp in source.GetType().GetProperties())
        {
            bool isMatched = target.GetType().GetProperties().Any(tProp => tProp.Name == sProp.Name && tProp.GetType() == sProp.GetType() && tProp.CanWrite);
            if (isMatched)
            {
                var value = sProp.GetValue(source);
                PropertyInfo propertyInfo = target.GetType().GetProperty(sProp.Name);
                propertyInfo.SetValue(target, value);
            }
        }
        return target;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 2017-05-08
    • 2014-02-27
    • 1970-01-01
    • 2016-12-21
    • 2018-02-01
    • 2016-10-13
    相关资源
    最近更新 更多