Ejemplo n.º 1
0
        public bool Insert(TEntity entity, IUnitOfWork uow = null, string tableName = null)
        {
            Check.NotNull(entity, nameof(entity));

            SetCreatedBy(entity);

            SetTenant(entity);

            var sql = _sql.Insert(tableName);

            if (EntityDescriptor.PrimaryKey.IsInt())
            {
                //自增主键
                sql += _sqlAdapter.IdentitySql;
                var id = ExecuteScalar <int>(sql, entity, uow);
                if (id > 0)
                {
                    EntityDescriptor.PrimaryKey.PropertyInfo.SetValue(entity, id);

                    _logger?.LogDebug("Insert:({0}),NewID({1})", sql, id);

                    return(true);
                }

                return(false);
            }

            if (EntityDescriptor.PrimaryKey.IsLong())
            {
                //自增主键
                sql += _sqlAdapter.IdentitySql;
                var id = ExecuteScalar <long>(sql, entity, uow);
                if (id > 0)
                {
                    EntityDescriptor.PrimaryKey.PropertyInfo.SetValue(entity, id);

                    _logger?.LogDebug("Insert:({0}),NewID({1})", sql, id);

                    return(true);
                }
                return(false);
            }

            if (EntityDescriptor.PrimaryKey.IsGuid())
            {
                var id = (Guid)EntityDescriptor.PrimaryKey.PropertyInfo.GetValue(entity);
                if (id == Guid.Empty)
                {
                    EntityDescriptor.PrimaryKey.PropertyInfo.SetValue(entity, _sqlAdapter.GenerateSequentialGuid());
                }

                _logger?.LogDebug("Insert:({0}),NewID({1})", sql, id);

                return(Execute(sql, entity, uow) > 0);
            }

            _logger?.LogDebug("Insert:({0})", sql);
            return(Execute(sql, entity, uow) > 0);
        }