Example #1
0
        public TEntity Create(TEntity entity)
        {
            Dictionary <string, object> modifiedProperties;

            if (DynamicProxy.IsProxy(entity.GetType()))
            {
                modifiedProperties = DynamicProxy.GetModifiedProperties(entity);
            }
            else
            {
                modifiedProperties = this._entityMapper.GetPropertyValues(entity);
            }
            List <string>           values = new List <string>();
            List <string>           list2  = new List <string>();
            List <IDbDataParameter> list3  = new List <IDbDataParameter>();

            foreach (PropertyInfo info in this._properties)
            {
                if (this._autoIncrementProperty != info)
                {
                    values.Add("[" + info.Name + "]");
                    list2.Add("@" + info.Name);
                    IDbDataParameter item = this._helper.CreateParameter(Xinchen.DbEntity.DbHelper.TypeMapper[info.PropertyType], "@" + info.Name, DBNull.Value);
                    if (modifiedProperties.ContainsKey(info.Name))
                    {
                        item.Value = modifiedProperties[info.Name];
                    }
                    if (this._keyProperty == info)
                    {
                        int result = 0;
                        if (int.TryParse(Convert.ToString(item.Value), out result) && (result <= 0))
                        {
                            throw new EntityException("检测到主键值为" + result.ToString() + ",是否忘记给主键赋值?实体名:" + this._entityType.Name);
                        }
                    }
                    if (item.Value == null)
                    {
                        item.Value = DBNull.Value;
                    }
                    list3.Add(item);
                }
            }
            string sql = string.Format("insert into {0} ({1}) values({2});", "[" + this.TableName + "]", string.Join(",", values), string.Join(",", list2));

            if (this._autoIncrementProperty != null && DbHelper.ProviderName != "System.Data.OleDb")
            {
                sql = sql + "SELECT @@IDENTITY;";
                int num2 = this._helper.ExecuteScalarCount(sql, list3.ToArray());
                if (this._autoIncrementProperty != null)
                {
                    this._entityMapper.SetValue(entity, this._autoIncrementProperty.Name, num2);
                }
            }
            else
            {
                this._helper.ExecuteUpdate(sql, list3.ToArray());
            }
            return(DynamicProxy.CreateDynamicProxy <TEntity>(entity));
        }