C# Reflection – Clone Value from a Source Object to Destination Object with Ignore Field

C# Reflection – Clone Value from a Source Object to Destination Object with Ignore Field

 
   using System;
   using System.Collections.Generic;
   using System.Linq;
   using System.Text;
   using System.Reflection;
   using System.Text.RegularExpressions;
 
   public class Reflect
   {
      public static void PassValue<T>(T src, T dest, string[] fieldignore)
      {
         BindingFlags flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;
 
         foreach (FieldInfo field in dest.GetType().GetFields(flags))
         {
            if(IsAcceptField(field.Name, fieldignore))
               field.SetValue(dest, field.GetValue(src));
         }
      }
 
      private static bool IsAcceptField(string field, string[] ignorefield)
      {
         var regex = new Regex(@"^\<(?<propertyName>\w+)\>k__BackingField$");
         var match = regex.Match(field);
 
         string srcfield = match.Groups.Count > 1 ? match.Groups[1].Value : field;
 
         return !ignorefield.Contains(srcfield);
      }
   }
 

Remarks :
The Function can be used on the Entity Framework Update for the AutoMapper Model.
– Source Object is from AutoMapper Model Object.
– Destination Object is got from the Database by using Entity Framework first.
   Then, the Value would be assigned from Source AutoMapper Model Object to the Destination Object by using the above Function.
   Finally, the Prepared Object would be passed to the Entity Framework for Updating on the Database Table.
   The Value Assignment from the above Function can be added more Validation from the Code Logic.