实体类相同属性间赋值与如何判断实体类中是否所有的字段都为null

1,实体类相同属性间赋值
/// 
        /// 将实体2的值动态赋值给实体1(名称一样的属性进行赋值)
        /// 
        /// 实体1
        /// 实体2
        /// 赋值后的model1
        protected static T1 BindModelValue(T1 model1, T2 model2) where T1 : class where T2 : class
        {
            if (model2 != null)
            {
                Type t1 = model1.GetType();
                Type t2 = model2.GetType();
                PropertyInfo[] property2 = t2.GetProperties();
                //排除主键
                List<string> exclude = new List<string>() { "Id" };
                foreach (PropertyInfo p in property2)
                {
                    if (exclude.Contains(p.Name)) { continue; }
                    t1.GetProperty(p.Name)?.SetValue(model1, p.GetValue(model2, null));
                }
                return model1;
            }
            return null;
        }
View Code
2、判断实体类中是否所有的字段都为null
 public static Boolean IsPropNull(Object obj)
        {
            Type t = obj.GetType();
            PropertyInfo[] props = t.GetProperties();
            foreach (var item in props)
            {
                //排除主键id
                if (item.Name == "Id") { continue; }
                //一旦有不为null的值,就返回true
                if (item.GetValue(obj) != null)
                {
                    return true;
                }
            }
            return false;
        }
View Code

 

转载于:https://www.cnblogs.com/wsl2011/p/11098229.html

你可能感兴趣的:(实体类相同属性间赋值与如何判断实体类中是否所有的字段都为null)