Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将属性从一个.net对象复制到另一个.net对象_C#_.net - Fatal编程技术网

C# 如何将属性从一个.net对象复制到另一个.net对象

C# 如何将属性从一个.net对象复制到另一个.net对象,c#,.net,C#,.net,我试图找到一种方法,将发布到web服务的对象保存到由实体管理的数据库中 我不想手动复制每个属性,而是想找到一种不用编写太多代码就能复制所有属性的方法 例如:objectFromClient.Copy(objectToDatabase) 这将为我节省多行代码来复制每个属性。我喜欢这个问题中给出的建议代码 但是,这对实体跟踪的对象不起作用,因为不能在实体中修改关键属性 我做了一些修改来跳过标记为EntityKey的列 我不确定这是否是一个正确的方法。有人能评论一下吗 using System; u

我试图找到一种方法,将发布到web服务的对象保存到由实体管理的数据库中

我不想手动复制每个属性,而是想找到一种不用编写太多代码就能复制所有属性的方法

例如:objectFromClient.Copy(objectToDatabase)

这将为我节省多行代码来复制每个属性。我喜欢这个问题中给出的建议代码

但是,这对实体跟踪的对象不起作用,因为不能在实体中修改关键属性

我做了一些修改来跳过标记为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);
        }
    }
}
使用系统;
使用System.Data.Objects.DataClass;
使用System.Linq;
运用系统反思;
/// 
///反射类型函数的静态类
/// 
公共静态类反思
{
/// 
///将属性复制到目标对象的“对象”扩展。
/// 
///消息来源。
///目的地。
公共静态void CopyProperties(此对象源、对象目标)
{
//如果此null中存在任何异常,则抛出异常
如果(源==null | |目标==null)
抛出新异常(“源或/和目标对象为空”);
//获取对象的类型
键入typeDest=destination.GetType();
类型typeSrc=source.GetType();
//收集所有要映射的有效属性
var results=来自typeSrc.GetProperties()中的srcProp
让targetProperty=typeDest.GetProperty(srcProp.Name)
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)。其中(a=>a是EdmScalarPropertyAttribute&((EdmScalarPropertyAttribute)a)。EntityKeyProperty)。Count()==0
&&srcProp.Name!=“EntityKey”
选择新{sourceProperty=srcProp,targetProperty=targetProperty};
//映射属性
foreach(结果中的var支柱)
{
//System.Diagnostics.Debug.WriteLine(props.targetProperty.Name);
props.targetProperty.SetValue(目标,props.sourceProperty.GetValue(源,null),null);
}
}
}
我不想手动复制每个属性,而是想找到一种不用编写太多代码就能复制所有属性的方法

你试过AutoMapper吗?看看这个

AutoMapper是一个简单的小型库,用于解决一个看似复杂的问题——摆脱将一个对象映射到另一个对象的代码


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

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

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;
    }
私有静态目标CopyProperties(源、目标)
{
foreach(source.GetType().GetProperties()中的var sProp)
{
bool isMatched=target.GetType().GetProperties().Any(tProp=>tProp.Name==sProp.Name&&tProp.GetType()==sProp.GetType()&&tProp.CanWrite);
如果(已匹配)
{
var value=sProp.GetValue(源);
PropertyInfo PropertyInfo=target.GetType().GetProperty(sProp.Name);
propertyInfo.SetValue(目标,值);
}
}
回报目标;
}

如果您知道此代码存在问题,您可以将其发布在此处。如果这段代码有效,并且您正在寻找一个评审,您可能会在上过得更好。它可能适合我的需要。谢谢你指给我看。但是这个简单的扩展方法看起来更干净。