示例#1
0
        /// <summary>
        /// 更新Entity除id外所有属性值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="db"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static T UpDate <T>(T db, T model) where T : IDbEntity
        {
            if (db == null)
            {
                EnginePersistenceLogger Log = ProcessEngineLogger.PersistenceLogger;
                Log.LogDebug("更新数据失败", string.Format("EF缓存/数据库中找不到{0} Id:{1}", typeof(T).Name, model.Id));
                throw new System.Exception(string.Format("更新数据失败 EF缓存/数据库中找不到{0} Id:{1}", typeof(T).Name, model.Id));
            }
            if (db.Id != model.Id)
            {
                throw new System.Exception($"id不同 {typeof(T).Name} db.id:{db.Id} model.id{model.Id}");
            }
            Type t = typeof(T);

            foreach (PropertyInfo item in t.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                if (item.Name == "Id")
                {
                    continue;
                }
                if (item.GetMethod != null && item.SetMethod != null)
                {
                    try
                    {
                        var resultVal = item.GetValue(model);
                        if (resultVal != null)
                        {
                            item.SetValue(db, item.GetValue(model));
                        }
                    }
                    catch (ArgumentException e)
                    {
                        throw new ArgumentException($"Update异常:类型 {t.Name } 属性 {item.Name}", e);
                    }
                }
            }
            return(db);
        }