best way to project ViewModel back into Model

前端 未结 3 431
天涯浪人
天涯浪人 2021-01-11 20:30

Consider having ViewModel :

public class ViewModel
{
    public int id {get;set;}
    public int a {get;set;}
    public int b {get;set;}
}

3条回答
  •  梦毁少年i
    2021-01-11 20:55

    For this purpose we have written a simple mapper. It maps by name and ignores virtual properties (so it works with entity framework). If you want to ignore certain properties add a PropertyCopyIgnoreAttribute.

    Usage:

    PropertyCopy.Copy(vm, dbmodel);
    PropertyCopy.Copy(dbmodel, vm);
    

    Code:

    public static class PropertyCopy
    {
        public static void Copy(TDest destination, TSource source)
            where TSource : class
            where TDest : class
        {
            var destProperties = destination.GetType().GetProperties()
                .Where(x => !x.CustomAttributes.Any(y => y.AttributeType.Name == PropertyCopyIgnoreAttribute.Name) && x.CanRead && x.CanWrite && !x.GetGetMethod().IsVirtual);
            var sourceProperties = source.GetType().GetProperties()
                .Where(x => !x.CustomAttributes.Any(y => y.AttributeType.Name == PropertyCopyIgnoreAttribute.Name) && x.CanRead && x.CanWrite && !x.GetGetMethod().IsVirtual);
            var copyProperties = sourceProperties.Join(destProperties, x => x.Name, y => y.Name, (x, y) => x);
            foreach (var sourceProperty in copyProperties)
            {
                var prop = destProperties.FirstOrDefault(x => x.Name == sourceProperty.Name);
                prop.SetValue(destination, sourceProperty.GetValue(source));
            }
        }
    }
    

提交回复
热议问题