Exemplo n.º 1
0
        /// <summary>
        /// 根据数据模型创建执行对象。
        /// </summary>
        /// <param name="type">执行对象类型</param>
        /// <param name="model">数据模型</param>
        /// <returns></returns>
        public static IExecuteObject CreateExecuteObject(ExecuteType type, object model = null)
        {
            if (model == null)
            {
                return(CreateEmptyExecuteObject(type));
            }

            PropertyInfo[] ps = model.GetType().GetProperties();

            IExecuteObject e = CreateEmptyExecuteObject(type);

            if (e == null)
            {
                return(null);
            }

            e.ExecuteType = type;
            e.TableName   = model.ToString();
            int i = e.TableName.LastIndexOf('.');

            if (i > -1)
            {
                e.TableName = e.TableName.Substring(i + 1, e.TableName.Length - i - 1);
            }

            //遍历实体类的所有 PropertyInfo
            foreach (var info in ps)
            {
                object val = info.GetValue(model, null);
                bool   chk = true;
                //检测初始化值是否超出范围
                if (info.PropertyType == typeof(DateTime))
                {
                    chk = (Convert.ToDateTime(val) >= new DateTime(1753, 1, 1, 12, 0, 0) && Convert.ToDateTime(val) <= new DateTime(9999, 12, 31, 11, 59, 59));
                }
                if (chk)
                {
                    //解析LinQ对象
                    //遍历 PropertyInfo 的所有 ColumnAttribute
                    foreach (ColumnAttribute attr in info.GetCustomAttributes(typeof(ColumnAttribute), false))
                    {
                        //是主键
                        if (attr.IsPrimaryKey)
                        {
                            e.PrimaryKey   = info.Name;
                            e.PrimaryValue = val;
                        }
                        //由数据库自动生成
                        if (attr.IsDbGenerated)
                        {
                            e.AutoColumns.Add(info.Name);
                        }
                        //可写
                        if (info.CanWrite)
                        {
                            if (val != null)
                            {
                                e.Add(info.Name, val);
                            }
                        }
                    }
                }
            }
            return(e);
        }