/// <summary>
        /// Complete sync entity
        /// </summary>
        /// <param name="tableModel"></param>
        /// <param name="table"></param>
        private async Task SyncEntityFieldsAsync(SynchronizeTableViewModel tableModel, TableModel table)
        {
            var resultModel = await _context.Table
                              .AsNoTracking()
                              .Include(x => x.TableFields)
                              .FirstOrDefaultAsync(x => x.Id == table.Id);

            if (resultModel == null)
            {
                return;
            }
            {
                if (tableModel.IsStaticFromEntityFramework)
                {
                    await SyncEntityFromEntityFramework(tableModel, resultModel.Id);
                }
                else
                {
                    var fieldTypeList   = _context.TableFieldTypes.ToList();
                    var fieldConfigList = _context.TableFieldConfigs.ToList();

                    foreach (var item in tableModel.Fields)
                    {
                        foreach (var configViewModel in item.Configurations)
                        {
                            configViewModel.Name = fieldConfigList.FirstOrDefault(x => x.Code == configViewModel.ConfigCode)?.Name;

                            if (configViewModel.ConfigCode != "9999")
                            {
                                continue;
                            }
                            if (configViewModel.Value == "systemcore")
                            {
                                configViewModel.Value = table.EntityType;
                            }
                        }

                        var insertField = _tablesService.AddFieldSql(item, tableModel.Name, _connectionString, true, table.EntityType);
                        // Save field model in the dataBase
                        if (!insertField.Result)
                        {
                            continue;
                        }
                        {
                            var configValues   = new List <TableFieldConfigValue>();
                            var tableFieldType = fieldTypeList.FirstOrDefault(x => x.Code == item.TableFieldCode);
                            if (tableFieldType == null)
                            {
                                continue;
                            }
                            var model = new TableModelField
                            {
                                DataType         = item.DataType,
                                TableId          = resultModel.Id,
                                Description      = item.Description,
                                Name             = item.Name,
                                DisplayName      = item.DisplayName,
                                AllowNull        = item.AllowNull,
                                Synchronized     = true,
                                TableFieldTypeId = tableFieldType.Id
                            };

                            foreach (var configItem in item.Configurations)
                            {
                                var config = fieldConfigList.FirstOrDefault(x => x.Code == configItem.ConfigCode);
                                if (config == null)
                                {
                                    continue;
                                }
                                configValues.Add(new TableFieldConfigValue
                                {
                                    TableFieldConfigId = config.Id,
                                    TableModelFieldId  = model.Id,
                                    Value = configItem.Value,
                                });
                            }

                            model.TableFieldConfigValues = configValues;
                            _context.TableFields.Add(model);
                            var dbResult = await _context.SaveAsync();

                            if (!dbResult.IsSuccess)
                            {
                                Debug.WriteLine(dbResult.Errors);
                            }
                        }
                    }
                }
            }
        }
        public async Task <IActionResult> AddField(CreateTableFieldViewModel field)
        {
            var entitiesList = _entityService.Tables;
            var table        = entitiesList.FirstOrDefault(x => x.Id == field.TableId);
            var tableName    = table?.Name;
            var schema       = table?.EntityType;

            field.EntitiesList = entitiesList.Select(x => x.Name).ToList();
            if (table == null)
            {
                ModelState.AddModelError(string.Empty, "Table not found");
                return(View(field));
            }

            var baseEntityProps = BaseModel.GetPropsName().Select(x => x.ToLower()).ToList();

            if (baseEntityProps.Contains(field.Name.Trim().ToLower()))
            {
                ModelState.AddModelError(string.Empty, "This field name can't be used, is system name!");
                return(View(field));
            }

            var configurationsRq = await _entityService.RetrieveConfigurationsOnAddNewTableFieldAsyncTask(field);

            if (configurationsRq.IsSuccess)
            {
                field.Configurations = configurationsRq.Result.ToList();
            }

            field = field.CreateSqlField();
            var insertField = _tablesService.AddFieldSql(field, tableName, ConnectionString, true, schema);

            // Save field model in the dataBase
            if (!insertField.Result)
            {
                ModelState.AddModelError(string.Empty, "Fail to apply changes to database!");
                return(View(field));
            }

            if (!table.IsCommon)
            {
                var isDynamic         = true;
                var isReference       = false;
                var referenceIsCommon = true;
                var tenants           = _organizationService.GetAllTenants().Where(x => x.MachineName != GearSettings.DEFAULT_ENTITY_SCHEMA).ToList();
                if (field.Parameter == FieldType.EntityReference)
                {
                    isReference = true;
                    var referenceTableName = field.Configurations
                                             .FirstOrDefault(x => x.Name == nameof(TableFieldConfigCode.Reference.ForeingTable))?.Value;

                    if (!referenceTableName.IsNullOrEmpty())
                    {
                        var refTable = await Context.Table.FirstOrDefaultAsync(x =>
                                                                               x.Name.Equals(referenceTableName) && x.EntityType.Equals(GearSettings.DEFAULT_ENTITY_SCHEMA) ||
                                                                               x.Name.Equals(referenceTableName) && x.IsPartOfDbContext);

                        if (refTable.IsPartOfDbContext)
                        {
                            isDynamic = false;
                        }
                        else if (!refTable.IsCommon)
                        {
                            referenceIsCommon = false;
                        }
                    }
                }

                foreach (var tenant in tenants)
                {
                    if (isDynamic && isReference && !referenceIsCommon)
                    {
                        var schemaConf = field.Configurations?.FirstOrDefault(x =>
                                                                              x.ConfigCode.Equals(TableFieldConfigCode.Reference.ForeingSchemaTable));
                        if (schemaConf != null)
                        {
                            var index = field.Configurations.IndexOf(schemaConf);
                            schemaConf.Value     = tenant.MachineName;
                            field.Configurations = field.Configurations.Replace(index, schemaConf).ToList();
                        }
                    }
                    _tablesService.AddFieldSql(field, tableName, ConnectionString, true, tenant.MachineName);
                }
            }

            var configs = field.Configurations.Select(item => new TableFieldConfigValue
            {
                TableFieldConfigId = item.ConfigId,
                Value = item.Value,
            }).ToList();

            var model = new TableModelField
            {
                DataType               = field.DataType,
                TableId                = field.TableId,
                Description            = field.Description,
                Name                   = field.Name,
                DisplayName            = field.DisplayName,
                AllowNull              = field.AllowNull,
                Synchronized           = true,
                TableFieldTypeId       = field.TableFieldTypeId,
                TableFieldConfigValues = configs
            };

            Context.TableFields.Add(model);
            var result = await Context.SaveAsync();

            if (result.IsSuccess)
            {
                RefreshRuntimeTypes();
                return(RedirectToAction("Edit", "Table", new { id = field.TableId, tab = "two" }));
            }

            ModelState.AppendResultModelErrors(result.Errors);

            return(View(field));
        }