Example #1
0
        public static void SetPropertyValue(BaseModel model, string propName, object value)
        {
            var prop = model.GetType().GetProperty(propName);

            prop.SetValue(model, value);
        }
Example #2
0
        /// <summary>
        /// 创建
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model">数据</param>
        /// <param name="tableName">表名</param>
        /// <param name="account">操作人账号</param>
        /// <returns>数据Id</returns>
        public Guid Create(BaseModel model)
        {
            string        account = _identity == null ? "WUWUYAOYAO" : _identity.UserAccount;
            Guid          guid    = model.BaseId == null || model.BaseId == Guid.Empty ? Guid.NewGuid() : model.BaseId;
            StringBuilder sb      = new StringBuilder();
            DateTime      date    = DateTimeUtils.NowBeijing();

            string[] exceptColoumns = { model.ModelName + "Id", "CreatedOn", "CreatedBy", "ModifiedOn", "ModifiedBy", "Id", "BaseId", "ModelName" };
            sb.AppendFormat("INSERT INTO {0} ({0}Id, CreatedOn, CreatedBy, ModifiedOn, ModifiedBy", model.ModelName);
            foreach (PropertyInfo property in model.GetType().GetProperties())
            {
                if (exceptColoumns.Contains(property.Name))
                {
                    continue;
                }
                sb.Append("," + property.Name);
            }
            sb.AppendFormat(") VALUES(@{0}Id, @CreatedOn, @CreatedBy, @ModifiedOn, @ModifiedBy", model.ModelName);
            Dictionary <string, object> paramList = new Dictionary <string, object>()
            {
                { "@" + model.ModelName + "Id", guid },
                { "@CreatedOn", date },
                { "@CreatedBy", account },
                { "@ModifiedOn", date },
                { "@ModifiedBy", account },
            };

            foreach (PropertyInfo property in model.GetType().GetProperties())
            {
                if (exceptColoumns.Contains(property.Name))
                {
                    continue;
                }
                sb.Append(",@" + property.Name);
                if (property.PropertyType.Name.ToLower() == "datetime")
                {
                    if ((DateTime)property.GetValue(model, null) != DateTime.MinValue)
                    {
                        paramList.Add("@" + property.Name, property.GetValue(model, null));
                    }
                    else
                    {
                        paramList.Add("@" + property.Name, Cast.NullDateTime);
                    }
                }
                else if (property.PropertyType.Name.ToLower() == "guid")
                {
                    paramList.Add("@" + property.Name, property.GetValue(model, null));
                }
                else
                {
                    if (property.GetValue(model, null) != null)
                    {
                        paramList.Add("@" + property.Name, property.GetValue(model, null));
                    }
                    else
                    {
                        sb.Replace("," + property.Name, "").Replace(",@" + property.Name, "");
                    }
                }
            }
            sb.Append(")");
            Execute(sb.ToString(), paramList);
            return(guid);
        }
        /// <summary>
        /// Method for insert entity into the database
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public virtual bool Create(BaseModel model)
        {
            StringBuilder columns      = new StringBuilder();
            StringBuilder columnValues = new StringBuilder();

            string tableName = model.GetType().Name.Insert(model.GetType().Name.Length, "s");

            var properties = model.GetType()
                             .GetProperties()
                             .Where(o => !o.Name.Equals("Id"));
            var propertyId = model.GetType().GetProperty("Id");

            foreach (var prop in properties)
            {
                if (prop.PropertyType.BaseType.Name.Equals("BaseModel"))
                {
                    columns.Append(string.Format("{0}Id,", prop.Name));
                }
                else
                {
                    columns.Append(string.Format("{0},", prop.Name));
                }
            }
            string columnsLine = columns.ToString().Substring(0, columns.ToString().Length - 1);

            foreach (var prop in properties)
            {
                if (prop.PropertyType.BaseType.Name.Equals("BaseModel"))
                {
                    BaseModel obj = (BaseModel)prop.GetValue(model);
                    columnValues.Append(string.Format("'{0}',", obj.Id));
                }
                else
                {
                    columnValues.Append(string.Format("'{0}',", prop.GetValue(model)));
                }
            }
            string columnValuesLine = columnValues.ToString().Substring(0, columnValues.ToString().Length - 1);

            int newId = GetUniqueKey(tableName);

            columnsLine      = columnsLine.Insert(0, string.Format("{0}, ", propertyId.Name));
            columnValuesLine = columnValuesLine.Insert(0, string.Format("'{0}', ", newId));

            string querySql = string.Format(SqlQueriesHelper.Insert, tableName, columnsLine, columnValuesLine);

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (var query = new SqlCommand())
                {
                    try
                    {
                        query.Connection  = connection;
                        query.CommandText = querySql;
                        query.Connection.Open();
                        query.ExecuteNonQuery();
                        query.Connection.Close();
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        return(false);
                    }
                }
            }
        }
Example #4
0
        public virtual int Update(BaseModel baseModel, string field)
        {
            #region Khai bao bien connection

            string        TableName = baseModel.GetType().Name.Substring(0, baseModel.GetType().Name.Length - 5);
            object        value;
            SqlConnection conn = new SqlConnection(Global.ConnectionString);
            string        sql  = DBUtils.SQLUpdate(baseModel, field);
            SqlCommand    cmd  = conn.CreateCommand();
            cmd.CommandTimeout = 0;
            cmd.CommandType    = CommandType.Text;
            cmd.CommandText    = sql;

            #endregion

            #region Gan gia tri cho command Goc
            PropertyInfo[] propertiesName = baseModel.GetType().GetProperties();
            for (int i = 0; i < propertiesName.Length; i++)
            {
                SqlDbType dbType = DBUtils.ConvertToSQLType(propertiesName[i].PropertyType);
                value = propertiesName[i].GetValue(baseModel, null);

                if (value != null)
                {
                    if (propertiesName[i].PropertyType.Equals(typeof(DateTime)))
                    {
                        if ((DateTime)value == DateTime.MinValue)
                        {
                            value = DefValues.Sql_MinDate;
                        }
                    }
                    if (propertiesName[i].PropertyType.Name.Equals("Byte[]"))
                    {
                        cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.Image).Value = value;
                    }
                    else
                    {
                        cmd.Parameters.Add("@" + propertiesName[i].Name, dbType).Value = value;
                    }
                }
                else
                {
                    cmd.Parameters.Add("@" + propertiesName[i].Name, dbType).Value = "";
                }
            }
            #endregion

            //#region Khai bao Log
            //if (!TableName.Equals("History"))
            //{
            //    mEL = new EventsLogModel();
            //    mEL.ObjectID = Convert.ToInt32(propertiesName[0].GetValue(baseModel, null));
            //    mEL.Action = "Update";
            //    mEL.TableName = TableName;
            //    mEL.UserID = Global.UserID;
            //}
            //#endregion

            try
            {
                conn.Open();
                return(cmd.ExecuteNonQuery());
                //cmd.Parameters.Clear();
                //#region Gan gia tri cho EventsLog

                //if (!TableName.Equals("History"))
                //{
                //    PropertyInfo[] propertiesName1 = mEL.GetType().GetProperties();
                //    sql = DBUtils.SQLInsert(mEL);

                //    for (int i = 0; i < propertiesName1.Length; i++)
                //    {
                //        value = propertiesName1[i].GetValue(mEL, null);

                //        if (!propertiesName1[i].Name.Equals("iD"))
                //        {
                //            if (value != null)
                //            {
                //                cmd.Parameters.Add("@" + propertiesName1[i].Name, DBUtils.ConvertToSQLType(propertiesName1[i].PropertyType)).Value = value;
                //            }
                //            else
                //            {
                //                cmd.Parameters.Add("@" + propertiesName1[i].Name, DBUtils.ConvertToSQLType(propertiesName1[i].PropertyType)).Value = "";
                //            }
                //        }
                //    }
                //}
                //#endregion
            }
            catch (SqlException se)
            {
                throw new Exception(se.Message);
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }
Example #5
0
        public virtual int Update(BaseModel baseModel)
        {
            #region Get systemDate
            DateTime sysTime = (DateTime)this.ExecuteScalar("EXEC spGetDateSystem");             //(DateTime)((DataTable)LoadDataFromSP("spGetDateSystem", "spGetDateSystem", null, null)).Rows[0][0];
            #endregion

            #region Khai bao bien connection

            string        TableName = baseModel.GetType().Name.Substring(0, baseModel.GetType().Name.Length - 5);
            object        value;
            SqlConnection conn = new SqlConnection(Global.ConnectionString);
            string        sql  = DBUtils.SQLUpdate(baseModel);
            SqlCommand    cmd  = conn.CreateCommand();
            cmd.CommandTimeout = 0;
            cmd.CommandType    = CommandType.Text;
            cmd.CommandText    = sql;

            #endregion

            #region Gan gia tri cho command Goc
            PropertyInfo[] propertiesName = baseModel.GetType().GetProperties();
            for (int i = 0; i < propertiesName.Length; i++)
            {
                object[] arrAtt = propertiesName[i].GetCustomAttributes(true);
                if (arrAtt.Length > 0)
                {
                    continue;
                }
                SqlDbType dbType = DBUtils.ConvertToSQLType(propertiesName[i].PropertyType);
                value = propertiesName[i].GetValue(baseModel, null);

                if (propertiesName[i].Name.ToLower().Equals("updatedby"))
                {
                    cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.NVarChar).Value = !String.IsNullOrEmpty(Global.AppUserName) ? Global.AppUserName : (value ?? "");
                }
                else if (propertiesName[i].Name.ToLower().Equals("updateddate") || propertiesName[i].Name.ToLower().Equals("updatedate"))
                {
                    cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.DateTime).Value = sysTime;
                }
                else if (propertiesName[i].Name.ToLower().Equals("userupdateid"))
                {
                    cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.Int).Value = Global.UserID != 0 ? Global.UserID : (value ?? 0);
                }
                else if (value != null)
                {
                    if (propertiesName[i].PropertyType.Equals(typeof(DateTime)))
                    {
                        if ((DateTime)value == DateTime.MinValue)
                        {
                            value = DefValues.Sql_MinDate;
                        }
                    }
                    if (propertiesName[i].PropertyType.Name.Equals("Byte[]"))
                    {
                        cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.Image).Value = value;
                    }
                    else
                    {
                        cmd.Parameters.Add("@" + propertiesName[i].Name, dbType).Value = value;
                    }
                }
                else
                {
                    if (propertiesName[i].PropertyType.Equals(typeof(DateTime?)))
                    {
                        cmd.Parameters.Add("@" + propertiesName[i].Name, dbType).Value = DBNull.Value;
                    }
                    else
                    {
                        cmd.Parameters.Add("@" + propertiesName[i].Name, dbType).Value = "";
                    }
                }
            }
            #endregion

            try
            {
                conn.Open();
                int rs = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return(rs);
                //cmd.CommandText = sql;
                //return cmd.ExecuteNonQuery();
            }
            catch (SqlException se)
            {
                throw new FacadeException(se.Message);
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }
        /// <summary>
        /// This method will validate a <see cref="BaseModel"/>.  Also, if the children of the given
        /// model need to be validated at the same time, it can do that as well.
        /// </summary>
        /// <param name="model">A <see cref="BaseModel"/> to validate.</param>
        /// <param name="validateChildren">If the chilren of the given model should be validated as well, supply true.</param>
        /// <returns>A boolean value indicating whether the validation was successful or not.</returns>
        /// <exception cref="InvalidOperationException">If the engine is not initialized</exception>
        public static bool ValidateModel(BaseModel model, bool validateChildren = false)
        {
            if (!_isInitialized)
                throw new InvalidOperationException("You must initialize the engine before it is used.");

            IEnumerable<object> validationErrors = CurrentValidator.ValidateModel(model);
            ValidationErrorCollection errorCollection = (model as IValidationInteraction).ValidationErrors;

            CurrentManager.SetErrors(errorCollection, validationErrors);

            //If we're validating the children as well.
            if (validateChildren)
            {
                IEnumerable<PropertyInfo> properties = model.GetType().GetProperties().Where(a => a.CanRead && typeof(BaseModel).IsAssignableFrom(a.PropertyType));
                IEnumerable<PropertyInfo> colProperties = model.GetType().GetProperties().Where(a => a.CanRead && typeof(IEnumerable<BaseModel>).IsAssignableFrom(a.PropertyType));

                foreach (PropertyInfo pi in properties)
                    ValidateModel((BaseModel)pi.GetValue(model, null), validateChildren);
                foreach (PropertyInfo pi in colProperties)
                {
                    foreach (BaseModel bm in (IEnumerable<BaseModel>)pi.GetValue(model, null))
                        ValidateModel(bm, validateChildren);
                }
            }

            return validationErrors.Count() == 0;
        }
Example #7
0
 public static List <object> GetIdParameter(this BaseModel model) => new List <object>
 {
     new SqliteParameter(model.GetType().Name, model.Id)
 };
        /// <summary>
        /// /////////////////////
        /// </summary>
        /// <param name="mode"></param>
        /// <returns></returns>
        public static string SQLInsert(BaseModel mode)
        {
            string tableName = mode.GetType().Name;

            tableName = tableName.Substring(0, tableName.Length - 5);

            string Insert = "insert into " + tableName + " (";

            PropertyInfo[] propertiesName = mode.GetType().GetProperties();

            for (int i = 0; i < propertiesName.Length; i++)
            {
                object[] arrAtt = propertiesName[i].GetCustomAttributes(true);
                if (arrAtt.Length > 0)
                {
                    continue;
                }
                if (!tableName.Equals("Tree_Members") && !tableName.Equals("PaymentTrans"))
                {
                    if (!propertiesName[i].Name.Equals("ID"))
                    {
                        Insert = Insert + propertiesName[i].Name;
                        Insert = Insert + ",";
                    }
                }
                else
                {
                    Insert = Insert + propertiesName[i].Name;
                    Insert = Insert + ",";
                }
            }
            Insert = Insert.Substring(0, Insert.Length - 1);
            Insert = Insert + ") values (";
            for (int i = 0; i < propertiesName.Length; i++)
            {
                object[] arrAtt = propertiesName[i].GetCustomAttributes(true);
                if (arrAtt.Length > 0)
                {
                    continue;
                }
                if (!tableName.Equals("Tree_Members") && !tableName.Equals("PaymentTrans"))
                {
                    if (!propertiesName[i].Name.Equals("ID"))
                    {
                        Insert = Insert + "@";
                        Insert = Insert + propertiesName[i].Name;
                        Insert = Insert + ",";
                    }
                }
                else
                {
                    Insert = Insert + "@";
                    Insert = Insert + propertiesName[i].Name;
                    Insert = Insert + ",";
                }
            }
            Insert = Insert.Substring(0, Insert.Length - 1);
            if (!tableName.Equals("Tree_Members") && !tableName.Equals("PaymentTrans"))
            {
                Insert = Insert + ") Select Scope_Identity()";
            }
            else
            {
                Insert = Insert + ")";
            }
            return(Insert);
        }
        private static async Task <bool> CreateOrUpdateDocument(BaseModel myObject) // true if success
        {
            if (NotInit)
            {
                return(false);
            }

            string id;
            string collectionId;

            if (myObject.GetType() == typeof(LiveEventEntry))
            {
                id           = ((LiveEventEntry)myObject).Id;
                collectionId = CollectionOutputs;
            }
            else if (myObject.GetType() == typeof(LiveEventSettingsInfo))
            {
                id           = ((LiveEventSettingsInfo)myObject).Id;
                collectionId = CollectionSettings;
            }
            else
            {
                return(false);
            }

            try
            {
                await _client.ReplaceDocumentAsync(
                    UriFactory.CreateDocumentUri(Database, collectionId, id), myObject);

                return(true);
            }
            catch (DocumentClientException de)
            {
                if (de.StatusCode != HttpStatusCode.NotFound)
                {
                    throw;
                }
            }

            try // new document
            {
                await _client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(Database, collectionId), myObject);

                return(true);
            }
            catch (DocumentClientException de)
            {
                if (de.StatusCode != HttpStatusCode.NotFound)
                {
                    throw;
                }
            }

            try // let create the db, collection, and document
            {
                // we use shared RU for the database (RU are shared among the collections)
                await _client.CreateDatabaseIfNotExistsAsync(new Database { Id = Database }, new RequestOptions { OfferThroughput = OfferThroughput });

                if (!DoNotUsePartitionMode)
                {
                    await _client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(Database), new DocumentCollection { Id = collectionId, PartitionKey = PartitionKeyDef });
                }
                else
                {
                    await _client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(Database), new DocumentCollection { Id = collectionId });
                }

                await _client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(Database, collectionId), myObject);

                return(true);
            }
            catch
            {
            }

            return(false);
        }
Example #10
0
 /// <summary>
 /// Xử lý nghiệp vụ sau khi lưu bản ghi thành công và không còn transaction
 /// </summary>
 /// <param name="baseModel"></param>
 public virtual void AfterCommit(BaseModel baseModel, ServiceResult serviceResponse)
 {
     //TODO
     serviceResponse.Data = this.GetByID(baseModel.GetType().Name, baseModel.GetPrimaryKeyValue().ToString());
 }
 public MappingNotImplementedException(BaseModel model)
     : base(message: "Mapper for provided domain model of type" + model.GetType() + " not found")
 {
     Model = model;
 }
Example #12
0
        public virtual Decimal Insert(BaseModel baseModel)
        {
            #region Get systemDate
            DateTime sysTime = (DateTime)((DataTable)LoadDataFromSP("spGetDateSystem", "spGetDateSystem", null, null)).Rows[0][0];
            #endregion

            #region Khai bao bien connection

            string        TableName = baseModel.GetType().Name.Substring(0, baseModel.GetType().Name.Length - 5);
            object        value;
            SqlConnection conn = new SqlConnection(Global.ConnectionString);
            string        sql  = DBUtils.SQLInsert(baseModel);
            SqlCommand    cmd  = conn.CreateCommand();
            cmd.CommandTimeout = 0;
            cmd.CommandType    = CommandType.Text;
            cmd.CommandText    = sql;

            #endregion

            #region Gan gia tri cho command goc

            PropertyInfo[] propertiesName = baseModel.GetType().GetProperties();
            for (int i = 0; i < propertiesName.Length; i++)
            {
                value = propertiesName[i].GetValue(baseModel, null);

                if (!TableName.Equals("Tree_Members") && !TableName.Equals("PaymentTrans"))
                {
                    if (!propertiesName[i].Name.Equals("ID") && !propertiesName[i].Name.Equals("iD"))
                    {
                        if (propertiesName[i].Name.ToLower().Equals("createdby") || propertiesName[i].Name.ToLower().Equals("updatedby"))
                        {
                            cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.NVarChar).Value = !String.IsNullOrEmpty(Global.AppUserName) ? Global.AppUserName : (value ?? "");
                        }
                        else if (propertiesName[i].Name.ToLower().Equals("createddate") || propertiesName[i].Name.ToLower().Equals("updateddate") || propertiesName[i].Name.ToLower().Equals("createdate") || propertiesName[i].Name.ToLower().Equals("updatedate"))
                        {
                            cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.DateTime).Value = sysTime;
                        }
                        else if (propertiesName[i].Name.ToLower().Equals("userinsertid") || propertiesName[i].Name.ToLower().Equals("userupdateid"))
                        {
                            cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.Int).Value = Global.UserID != 0 ? Global.UserID : (value ?? 0);
                        }
                        else if (value != null)
                        {
                            if (propertiesName[i].PropertyType.Equals(typeof(DateTime)))
                            {
                                if ((DateTime)value == DateTime.MinValue)
                                {
                                    value = DefValues.Sql_MinDate;
                                }
                            }
                            if (propertiesName[i].PropertyType.Name.Equals("Byte[]"))
                            {
                                cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.Image).Value = value;
                            }
                            else
                            {
                                cmd.Parameters.Add("@" + propertiesName[i].Name, DBUtils.ConvertToSQLType(propertiesName[i].PropertyType)).Value = value;
                            }
                        }
                        else
                        {
                            if (propertiesName[i].PropertyType.Equals(typeof(DateTime?)))
                            {
                                cmd.Parameters.Add("@" + propertiesName[i].Name, DBUtils.ConvertToSQLType(propertiesName[i].PropertyType)).Value = DBNull.Value;
                            }
                            else
                            {
                                cmd.Parameters.Add("@" + propertiesName[i].Name, DBUtils.ConvertToSQLType(propertiesName[i].PropertyType)).Value = "";
                            }
                        }
                    }
                }
                else
                {
                    if (value != null)
                    {
                        if (propertiesName[i].PropertyType.Name.Equals("Byte[]"))
                        {
                            cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.Image).Value = value;
                        }
                        else
                        {
                            cmd.Parameters.Add("@" + propertiesName[i].Name, DBUtils.ConvertToSQLType(propertiesName[i].PropertyType)).Value = value;
                        }
                    }
                    else
                    {
                        cmd.Parameters.Add("@" + propertiesName[i].Name, DBUtils.ConvertToSQLType(propertiesName[i].PropertyType)).Value = "";
                    }
                }
            }

            #endregion

            try
            {
                conn.Open();
                decimal id = (decimal)cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                //  cmd.ExecuteNonQuery();
                return(id);
            }
            catch (SqlException e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }
Example #13
0
 public static List <object> GetParameters <T>(this BaseModel item) where T : BaseModel, new()
 => GetFieldsFromTable(item.GetType()).Select(x => new SqliteParameter($"@{x.Name}", x.GetValue(item)))
 .OfType <object>()
 .ToList();
Example #14
0
 public static string ToDeleteQuery(this BaseModel model)
 {
     return($"DELETE FROM {model.GetType().Name} WHERE Id = @Id");
 }
Example #15
0
        /// <summary>
        /// Update dữ liệu thông qua Model
        /// -- Nguyễn Văn Thao - 29/9/2009 --
        /// </summary>
        /// <param name="baseModel">Model</param>
        public void Update(BaseModel baseModel)
        {
            #region Get systemDate
            DateTime sysTime = GetSystemDate();
            #endregion

            #region Khai bao cac bien connection
            string TableName = baseModel.GetType().Name.Substring(0, baseModel.GetType().Name.Length - 5);
            string sql       = DBUtils.SQLUpdate(baseModel);
            cmd             = new SqlCommand(sql, cnn, tran);
            cmd.CommandType = CommandType.Text;
            PropertyInfo[] propertiesName = baseModel.GetType().GetProperties();
            object         value;
            #endregion

            #region Gan cac bien vao command goc
            for (int i = 0; i < propertiesName.Length; i++)
            {
                SqlDbType dbType = DBUtils.ConvertToSQLType(propertiesName[i].PropertyType);
                value = propertiesName[i].GetValue(baseModel, null);

                if (propertiesName[i].Name.ToLower().Equals("updatedby"))
                {
                    cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.NVarChar).Value = !String.IsNullOrEmpty(Global.AppUserName) ? Global.AppUserName : (value ?? "");
                }
                else if (propertiesName[i].Name.ToLower().Equals("updateddate") || propertiesName[i].Name.ToLower().Equals("updatedate"))
                {
                    cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.DateTime).Value = sysTime;
                }
                else if (propertiesName[i].Name.ToLower().Equals("userupdateid"))
                {
                    cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.Int).Value = Global.UserID != 0 ? Global.UserID : (value ?? 0);
                }
                else if (value != null)
                {
                    if (propertiesName[i].PropertyType.Equals(typeof(DateTime)))
                    {
                        if ((DateTime)value == DateTime.MinValue)
                        {
                            value = DefValues.Sql_MinDate;
                        }
                    }
                    cmd.Parameters.Add("@" + propertiesName[i].Name, dbType).Value = value;
                }
                else
                {
                    if (propertiesName[i].PropertyType.Equals(typeof(DateTime?)))
                    {
                        cmd.Parameters.Add("@" + propertiesName[i].Name, dbType).Value = DBNull.Value;
                    }
                    else
                    {
                        cmd.Parameters.Add("@" + propertiesName[i].Name, dbType).Value = "";
                    }
                }
            }
            #endregion

            try
            {
                cmd.ExecuteNonQuery();
            }
            catch (SqlException se)
            {
                tran.Rollback();
                throw new Exception("Update " + baseModel.GetType().Name + " error :" + se.Message);
            }
        }
Example #16
0
        /// <summary>
        /// 复制对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static TEntity Clone <TEntity, T>(this BaseModel <T> entity) where TEntity : BaseModel <T>, new()
        {
            TEntity data = new TEntity();

            return((TEntity)Mapper.Instance.Map(entity, data, entity.GetType(), typeof(TEntity)));
        }
 public MappingNotImplementedException(BaseModel model)
     : base(message: "Mapper for provided domain model of type" + model.GetType() + " not found")
 {
     Model = model;
 }
Example #18
0
        public int Insert(BaseModel model)
        {
            Type          T   = model.GetType();
            StringBuilder sql = new StringBuilder("insert into ");

            sql.Append(tableName);
            sql.Append(" (");

            //循环对象的属性名:取得列名
            PropertyInfo[] propertys = T.GetProperties();

            StringBuilder sbColumns = new StringBuilder();
            StringBuilder sbValues  = new StringBuilder();

            string strIdentityName = "";

            foreach (PropertyInfo pro in propertys)
            {
                //取得是否有自动增长的特性
                IdentityAttribute att = Attribute.GetCustomAttribute(pro, typeof(IdentityAttribute)) as IdentityAttribute;
                if (att == null || !att.IsIdentity)
                {
                    if (sbColumns.Length > 0)
                    {
                        sbColumns.Append(",");
                        sbValues.Append(",");
                    }
                    if (pro.Name == "DataBase")
                    {
                        sbColumns.Append("[" + pro.Name + "]");
                    }
                    else
                    {
                        sbColumns.Append(pro.Name);
                    }

                    sbValues.Append("@" + pro.Name);
                }
                else
                {
                    strIdentityName = pro.Name;
                }
            }

            sql.Append(sbColumns.ToString());
            sql.Append(") values(" + sbValues.ToString() + ")");

            if (strIdentityName != "")
            {
                sql.Append("; select @@identity");
            }
            //循环取出对象的属性值:为列赋值
            DbParameters paras = new DbParameters();

            foreach (PropertyInfo pro in propertys)
            {
                //取得是否有自动增长的特性
                if (pro.Name != strIdentityName)
                {
                    object value = pro.GetValue(model);
                    if (value == null)
                    {
                        value = getDefault(pro);
                    }
                    paras.Add(pro.Name, value);
                }
            }

            this.db.Open();
            object result = db.ExecuteScalar(sql.ToString(), paras);

            this.db.Close();

            int SN = int.Parse(result.ToString());

            return(SN);
        }
        /// <summary>
        /// Call this method to clear all validation issues with a given model.
        /// </summary>
        /// <param name="model">A <see cref="BaseModel"/> to clear validation issues from.</param>
        /// <param name="clearChildIssues">A boolean value indicating whether or not to clear child objects issues as well.</param>
        public static void ClearValidationIssues(BaseModel model, bool clearChildIssues = false)
        {
            if (model == null)
                return;

            (model as IValidationInteraction).ValidationErrors.Clear();

            if (clearChildIssues)
            {
                IEnumerable<PropertyInfo> properties = model.GetType().GetProperties().Where(a => a.CanRead && typeof(BaseModel).IsAssignableFrom(a.PropertyType));
                IEnumerable<PropertyInfo> colProperties = model.GetType().GetProperties().Where(a => a.CanRead && typeof(IEnumerable<BaseModel>).IsAssignableFrom(a.PropertyType));

                foreach (PropertyInfo pi in properties)
                    ClearValidationIssues((BaseModel)pi.GetValue(model, null), clearChildIssues);
                foreach (PropertyInfo pi in colProperties)
                {
                    foreach (BaseModel bm in (IEnumerable<BaseModel>)pi.GetValue(model, null))
                        ClearValidationIssues(bm, clearChildIssues);
                }
            }
        }
Example #20
0
        public virtual int Update(BaseModel baseModel)
        {
            #region Get systemDate
            DateTime sysTime = (DateTime)((DataTable)LoadDataFromSP("spGetDateSystem", "spGetDateSystem", null, null)).Rows[0][0];
            #endregion

            #region Khai bao bien connection

            string        TableName = baseModel.GetType().Name.Substring(0, baseModel.GetType().Name.Length - 5);
            object        value;
            SqlConnection conn = new SqlConnection(Global.ConnectionString);
            string        sql  = DBUtils.SQLUpdate(baseModel);
            SqlCommand    cmd  = conn.CreateCommand();
            cmd.CommandTimeout = 6000;
            cmd.CommandType    = CommandType.Text;
            cmd.CommandText    = sql;

            #endregion

            #region Gan gia tri cho command Goc
            PropertyInfo[] propertiesName = baseModel.GetType().GetProperties();
            for (int i = 0; i < propertiesName.Length; i++)
            {
                SqlDbType dbType = DBUtils.ConvertToSQLType(propertiesName[i].PropertyType);
                value = propertiesName[i].GetValue(baseModel, null);

                if (propertiesName[i].Name.ToLower().Equals("updatedby"))
                {
                    cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.NVarChar).Value = !String.IsNullOrEmpty(Global.AppUserName) ? Global.AppUserName : (value ?? "");
                }
                else if (propertiesName[i].Name.ToLower().Equals("updateddate") || propertiesName[i].Name.ToLower().Equals("updatedate"))
                {
                    cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.DateTime).Value = sysTime;
                }
                else if (propertiesName[i].Name.ToLower().Equals("userupdateid"))
                {
                    cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.Int).Value = Global.UserID != 0 ? Global.UserID : (value ?? 0);
                }
                else if (value != null)
                {
                    if (propertiesName[i].PropertyType.Equals(typeof(DateTime)))
                    {
                        if ((DateTime)value == DateTime.MinValue)
                        {
                            value = DefValues.Sql_MinDate;
                        }
                    }
                    if (propertiesName[i].PropertyType.Name.Equals("Byte[]"))
                    {
                        cmd.Parameters.Add("@" + propertiesName[i].Name, SqlDbType.Image).Value = value;
                    }
                    else
                    {
                        cmd.Parameters.Add("@" + propertiesName[i].Name, dbType).Value = value;
                    }
                }
                else
                {
                    cmd.Parameters.Add("@" + propertiesName[i].Name, dbType).Value = "";
                }
            }
            #endregion

            #region Khai bao Log
            //if (!TableName.Equals("History"))
            //{
            //    mEL = new EventsLogModel();
            //    mEL.ObjectID = Convert.ToInt32(propertiesName[0].GetValue(baseModel, null));
            //    mEL.Action = "Update";
            //    mEL.TableName = TableName;
            //    mEL.UserID = Global.UserID;
            //}
            #endregion

            try
            {
                conn.Open();
                int rs = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                #region Gan gia tri cho EventsLog

                //if (!TableName.Equals("History"))
                //{
                //    PropertyInfo[] propertiesName1 = mEL.GetType().GetProperties();
                //    sql = DBUtils.SQLInsert(mEL);

                //    for (int i = 0; i < propertiesName1.Length; i++)
                //    {
                //        value = propertiesName1[i].GetValue(mEL, null);

                //        if (!propertiesName1[i].Name.Equals("iD"))
                //        {
                //            if (value != null)
                //            {
                //                cmd.Parameters.Add("@" + propertiesName1[i].Name, DBUtils.ConvertToSQLType(propertiesName1[i].PropertyType)).Value = value;
                //            }
                //            else
                //            {
                //                cmd.Parameters.Add("@" + propertiesName1[i].Name, DBUtils.ConvertToSQLType(propertiesName1[i].PropertyType)).Value = "";
                //            }
                //        }
                //    }
                //}
                #endregion
                return(rs);
                //cmd.CommandText = sql;
                //return cmd.ExecuteNonQuery();
            }
            catch (SqlException se)
            {
                throw new FacadeException(se.Message);
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }