zoukankan      html  css  js  c++  java
  • C# PropertyInfo 反射实体部分字段

    目的:将一个对象的字段赋值给另外一个对象,为空或默认值则不赋值

    关键代码:

    PropertyInfo[] props = typeof(hospital).GetProperties();
    foreach (PropertyInfo p in props)
    {
        if (p.PropertyType.FullName == "System.String" && p.GetValue(entity) != null)
            p.SetValue(model, p.GetValue(entity));
        if (p.PropertyType.FullName == "System.Guid" && p.GetValue(entity).ToString() != Guid.Empty.ToString())
            p.SetValue(model, p.GetValue(entity));
        if (p.PropertyType.FullName == "System.DateTime" && p.GetValue(entity).ToString() != Convert.ToDateTime("0001-01-01 00:00:00").ToString())
            p.SetValue(model, p.GetValue(entity));
        if (p.PropertyType.FullName == "System.SByte" && p.GetValue(entity).ToString() != null)
            p.SetValue(model, p.GetValue(entity));
    }

    具体代码:

    1.添加我们的实体类

    public class hospital
    {
        public Guid id { get; set; }
        public string hospital_id { get; set; }
        public string name { get; set; }
        public string acronym { get; set; }
        public DateTime create_time { get; set; }
        public sbyte? status { get; set; }
    }

    2.封装关键代码到公共类

    public class PropertyTrade
    {
        public static void Voluation<T>(T model, T entity)
        {
            PropertyInfo[] props = typeof(T).GetProperties();
            foreach (PropertyInfo p in props)
            {
                if (p.PropertyType.FullName == "System.String" && p.GetValue(entity) != null)
                    p.SetValue(model, p.GetValue(entity));
                if (p.PropertyType.FullName == "System.Guid" && p.GetValue(entity).ToString() != Guid.Empty.ToString())
                    p.SetValue(model, p.GetValue(entity));
                if (p.PropertyType.FullName == "System.DateTime" && p.GetValue(entity).ToString() != Convert.ToDateTime("0001-01-01 00:00:00").ToString())
                    p.SetValue(model, p.GetValue(entity));
                if (p.PropertyType.FullName == "System.SByte" && p.GetValue(entity).ToString() != null)
                    p.SetValue(model, p.GetValue(entity));
            }
        }
    }

    3.调用

    var entity = json.ToString().ToObject<hospital>();
    Expression<Func<hospital, bool>> filter = u => u.id == entity.id;
    var model = idal.GetAnyAsync(filter).Result.FirstOrDefault();
    if (model != null)
    {
        PropertyTrade.Voluation<hospital>(model, entity);
        int count = await idal.UpdateAsync(model);
        ……
    }
  • 相关阅读:
    【面霸2】
    【面霸1】php知识点
    【技术宅11】php入门运算
    【技术宅10】顺序二分查找算法
    【技术宅9】遍历一个文件夹下的所有文件和子文件夹
    【技术宅7】一个或多个虚拟主机配置方法
    【技术宅6】把一个无限级分类循环成tree结构
    【技术宅5】抓去网页数据的3种方法
    【技术宅4】如何把M个苹果平均分给N个小朋友
    【技术宅3】截取文件和url扩展名的N种方法
  • 原文地址:https://www.cnblogs.com/Allofus/p/14848681.html
Copyright © 2011-2022 走看看