public static class ObjectUtils
{
/// <summary>
/// 根据source创建一个强类型的Object,并根据相同属性名进行赋值.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static T CreateObject<T>(object source) where T : class, new()
{
var obj = new T();
var propertiesFromSource = source.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

foreach (var property in properties)
{
var sourceProperty = propertiesFromSource.FirstOrDefault(x => x.Name == property.Name);
if (sourceProperty != null)
{
property.SetValue(obj, sourceProperty.GetValue(source, null), null);
}
}

return obj;
}
/// <summary>
/// 根据source修改一个强类型的Target Object,并根据相同属性名进行赋值.
/// </summary>
/// <typeparam name="TTarget"></typeparam>
/// <typeparam name="TSource"></typeparam>
/// <param name="target"></param>
/// <param name="source"></param>
/// <param name="propertyExpressionsFromSource"></param>
public static void UpdateObject<TTarget, TSource>(TTarget target, TSource source, params Expression<Func<TSource, object>>[] propertyExpressionsFromSource)
where TTarget : class
where TSource : class
{
if (target == null)
{
throw new ArgumentNullException("target");
}
if (source == null)
{
throw new ArgumentNullException("source");
}
if (propertyExpressionsFromSource == null)
{
throw new ArgumentNullException("propertyExpressionsFromSource");
}

var properties = target.GetType().GetProperties();

foreach (var propertyExpression in propertyExpressionsFromSource)
{
var propertyFromSource = GetProperty<TSource, object>(propertyExpression);
var propertyFromTarget = properties.SingleOrDefault(x => x.Name == propertyFromSource.Name);
if (propertyFromTarget != null)
{
propertyFromTarget.SetValue(target, propertyFromSource.GetValue(source, null), null);
}
}
}

private static PropertyInfo GetProperty<TSource, TProperty>(Expression<Func<TSource, TProperty>> lambda)
{
var type = typeof(TSource);
MemberExpression memberExpression = null;

switch (lambda.Body.NodeType)
{
case ExpressionType.Convert:
memberExpression = ((UnaryExpression)lambda.Body).Operand as MemberExpression;
break;
case ExpressionType.MemberAccess:
memberExpression = lambda.Body as MemberExpression;
break;
}

if (memberExpression == null)
{
throw new ArgumentException(string.Format("Invalid Lambda Expression '{0}'.", lambda.ToString()));
}

var propInfo = memberExpression.Member as PropertyInfo;
if (propInfo == null)
{
throw new ArgumentException(string.Format("Expression '{0}' refers to a field, not a property.", lambda.ToString()));
}

if (type != propInfo.ReflectedType && !type.IsSubclassOf(propInfo.ReflectedType))
{
throw new ArgumentException(string.Format("Expresion '{0}' refers to a property that is not from type {1}.", lambda.ToString(), type));
}

return propInfo;
}
}

根据相同的字段创建或者修改一个Model的更多相关文章

  1. oracle 创建表、删除表、添加字段、删除字段、表备注、字段备注、修改表属性

    1.创建表 create table 表名( classid number() primary key, 表字段 数据类型 是否允许为空(not null:不为空/null:允许空) 默认值(defa ...

  2. 当进行数据查询时候 要考虑创建一个model ;具备传入与输出的字段

    当进行数据查询时候 要考虑创建一个model ;具备传入与输出的字段

  3. MySQL:创建、修改和删除表

    其实对很多人来说对于SQL语句已经忘了很多,或者说是不懂很多,因为有数据库图形操作软件,方便了大家,但是我们不能忘记最根本的东西,特别是一些细节上的东西,可能你用惯了Hibernate,不用写SQL语 ...

  4. SQLite 入门教程(二)创建、修改、删除表 (转)

    转于 SQLite 入门教程(二)创建.修改.删除表 一.数据库定义语言 DDL 在关系型数据库中,数据库中的表 Table.视图 View.索引 Index.关系 Relationship 和触发器 ...

  5. SQLite 入门教程(二)创建、修改、删除表

    一.数据库定义语言 DDL 在关系型数据库中,数据库中的表 Table.视图 View.索引 Index.关系 Relationship 和触发器 Trigger 等等,构成了数据库的架构 Schem ...

  6. hive -- 分区,分桶(创建,修改,删除)

    hive -- 分区,分桶(创建,修改,删除) 分区: 静态创建分区: 1. 数据: john doe 10000.0 mary smith 8000.0 todd jones 7000.0 boss ...

  7. Object.defineProperty() 方法会直接在一个对象上定义一个新属性,或者修改一个已经存在的属性, 并返回这个对象。

    Object.defineProperty() 方法会直接在一个对象上定义一个新属性,或者修改一个已经存在的属性, 并返回这个对象. 语法EDIT Object.defineProperty(obj, ...

  8. 使用 PowerShell 创建和修改 ExpressRoute 线路

    开始之前 安装最新版本的 Azure Resource Manager PowerShell cmdlet. 有关详细信息,请参阅 Azure PowerShell 概述. 在开始配置之前,请查看先决 ...

  9. 如何使用StarUML for Mac创建和修改元素

    StarUML for Mac是一款UML软件建模器,支持快速编辑中的许多缩写,一次创建元素和关系,如子类,支持接口等.如何使用StarUML for Mac创建和修改元素?下面我们来介绍一下. 如何 ...

随机推荐

  1. java中实现与.net的format格式化字符串输出

    Java中的格式化字符串 System.out.println(MessageFormat.format("name={0}", "张三")); .net中的格 ...

  2. Scala + Play + Sbt + Protractor

    Scala + Play + Sbt + Protractor = One Build 欢迎关注我的新博客地址:http://cuipengfei.me/ 我所在的项目的技术栈选用的是Play fra ...

  3. 设置checkbox为只读(readOnly)

    方式一: checkbox没有readOnly属性,如果使用disabled=“disabled”属性的话,会让checkbox变成灰色的,用户很反感这种样式可以这样让它保持只读:设置它的onclic ...

  4. Android高效开发环境(Genymotion,Gradle,Andriod Studio)

    临近十一,项目接近上线,终于有些碎片时间可以查看一些博客. 这篇博客是Android开发大牛Cyril Mottier在去年写的博客,我把它翻译一下共享给国内志同道合的朋友,同时也是对自己一个很好的锻 ...

  5. Markdown 代码测试!

    # Mou ![Mou icon](http://mouapp.com/Mou_128.png) ## Overview **Mou**, the missing Markdown editor fo ...

  6. 浅谈DevExpress<四>:TreeList中的拖拽功能

    本篇要实现的目标,简单来说就是把一个treelist的节点用鼠标拖到另外的节点(自身或其他的listview)上,如下图: 1 

  7. Push Notification总结系列(二)

    Push Notification系列概括: 1.Push Notification简介和证书说明及生成配置 2.Push Notification的iOS处理代码和Provider详解 3.Push ...

  8. 1572: [Usaco2009 Open]工作安排Job[贪心]

    Description Farmer John 有太多的工作要做啊!!!!!!!!为了让农场高效运转,他必须靠他的工作赚钱,每项工作花一个单位时间. 他的工作日从0时刻开始,有1000000000个单 ...

  9. D6

    今天依旧很惨...本来第二题可以A的,感觉很久没有碰数学,出现这样的低级错误,简直逗了...晚上的话打算找了书店,静下心来看点书进去吧 但是其他题目就不太好写了..我直接发题解好了 T1:贪心 其实贪 ...

  10. MySQL关联查询总结

    MySQL中经常使用关联查询,有机会总结下: 1 left join(左联查询): 返回包括左表中的所有记录和右表中联接字段相等的记录 例:select * from a left join b on ...