public bool Persist <T>(_Entity entity) { entity.Code = entity.Code.ToUpper(); entity.EntryDate = GameManager.GetCurrentTimestamp(); entity.FlagActive = true; return(_db.Persist <T>(entity)); }
public bool Merge <T>(_Entity entity) { Debug.Log("Merge in collection: " + typeof(T)); MongoCollection <T> collection = _instance._db.GetCollection <T>(typeof(T).ToString()); var retorno = collection.Save(entity); return(retorno.Ok); }
public bool Persist <T>(_Entity entity) { Debug.Log("Persist in collection: " + typeof(T)); MongoCollection <T> collection = _instance._db.GetCollection <T>(typeof(T).ToString()); var retorno = collection.Insert(entity); return(retorno.Ok); }
public void RemoveEntity(_Entity entity) { if (entity is Player) { player = null; } else if (entity is _Agent) { agent = null; } else if (entity is Thing) { thing = null; } else { throw new BadEntityException("Tried to remove " + entity.ToString() + " from " + ToString()); } }
public void AssignEntity(_Entity entity) { if (entity is Player) { player = (Player)entity; } else if (entity is _Agent) { agent = (_Agent)entity; } else if (entity is Thing) { thing = (Thing)entity; } else { throw new BadEntityException("Tried to assign " + entity.ToString() + " to " + ToString()); } }
/// <summary> /// Получить количество экземпляров сущности. /// </summary> /// <param name="_entityId">Идентификатор сущности.</param> /// <returns>Количество обобщенных сущностей.</returns> public int GetEntitiesCount( int _entityId) { using (var uow = this.CreateAdminUnitOfWork()) { _Entity entity = uow._EntityRepository.GetById(_entityId); string query = $"SELECT COUNT(*) " + $"{Environment.NewLine}FROM {entity.DatabaseScheme}.\"{entity.DatabaseName}\";"; int result = uow._DynamicRepository.Sql(query) .Select(e => { return(Int32.TryParse(e.FirstOrDefault().Value?.ToString(), out int count) ? count : 0); }) .FirstOrDefault(); return(result); } }
public void Persist <T>(_Entity entity) { if (typeof(T) == typeof(User)) { UserController.Create((User)entity); } else if (typeof(T) == typeof(AppLocale)) { AppLocaleController.Create((AppLocale)entity); } else if (typeof(T) == typeof(AppText)) { AppTextController.Create((AppText)entity); } else if (typeof(T) == typeof(Bank)) { BankController.Create((Bank)entity); } else if (typeof(T) == typeof(Battle)) { BattleController.Create((Battle)entity); } else if (typeof(T) == typeof(City)) { CityController.Create((City)entity); } else if (typeof(T) == typeof(Harbor)) { HarborController.Create((Harbor)entity); } else if (typeof(T) == typeof(Inventory)) { InventoryController.Create((Inventory)entity); } else if (typeof(T) == typeof(Item)) { ItemController.Create((Item)entity); } else if (typeof(T) == typeof(Market)) { MarketController.Create((Market)entity); } else if (typeof(T) == typeof(Powerup)) { PowerupController.Create((Powerup)entity); } else if (typeof(T) == typeof(ProfileAI)) { ProfileAiController.Create((ProfileAI)entity); } else if (typeof(T) == typeof(Quest)) { QuestController.Create((Quest)entity); } else if (typeof(T) == typeof(Resource)) { ResourceController.Create((Resource)entity); } else if (typeof(T) == typeof(Reward)) { RewardController.Create((Reward)entity); } else if (typeof(T) == typeof(Scenario)) { ScenarioController.Create((Scenario)entity); } else if (typeof(T) == typeof(UserGame)) { UserGameController.Create((UserGame)entity); } else if (typeof(T) == typeof(Vessel)) { VesselController.Create((Vessel)entity); } else if (typeof(T) == typeof(Weapon)) { WeaponController.Create((Weapon)entity); } else { throw new Exception("Controller not implemented yet."); } }
/// <summary> /// Получить список экземпляров сущности. /// </summary> /// <param name="_entityId">Идентификатор сущности.</param> /// <param name="sort_FieldId">Идентификатор поля для сортировки.</param> /// <param name="sortDirection">Идентификатор направления сортировки.</param> /// <param name="filters">Фильтры.</param> /// <param name="pageSize">Размер страницы.</param> /// <param name="pageNumber">Номер страницы.</param> /// <returns>Список обобщенных сущностей.</returns> public List <_GenericEntity> GetEntitiesList( int _entityId, int?sort_FieldId = null, SortDirections sortDirection = SortDirections.Ascending, List <_GenericEntityFieldFilter> filters = null, int pageSize = 1000, int pageNumber = 0) { using (var uow = this.CreateAdminUnitOfWork()) { _Entity entity = uow._EntityRepository.GetById(_entityId); List <_Field> fields = uow._FieldRepository.Query(entityId: _entityId); _Field sortField = fields.FirstOrDefault(f => f.Id == sort_FieldId) ?? fields.First(); IEnumerable <string> selectList = fields.Select(f => { switch (f._FieldTypeId) { case (int)_FieldTypes.Integer: case (int)_FieldTypes.Decimal: return($"CAST({f.DatabaseName} AS TEXT) AS f_{f.Id}"); case (int)_FieldTypes.DateTime: return($"TO_CHAR({f.DatabaseName}, '{SQL_DATE_TIME_FORMAT}') AS f_{f.Id}"); default: return($"{f.DatabaseName} AS f_{f.Id}"); } }); filters = filters ?? new List <_GenericEntityFieldFilter>(); IEnumerable <string> filterList = filters.Select(f => { var field = fields.FirstOrDefault(x => x.Id == f._FieldId); Argument.Require(field != null, "Не найдено поле сущности для фильтра."); object deserializedValue = _DeserializeField(f.Value, field._FieldTypeId); string sqlValue = _ToSqlField(deserializedValue, field._FieldTypeId); return($"{field.DatabaseName} = {sqlValue}"); }); string query = $"SELECT " + $"{Environment.NewLine}{string.Join($"{Environment.NewLine}, ", selectList)} " + $"{Environment.NewLine}FROM {entity.DatabaseScheme}.\"{entity.DatabaseName}\" " + (!filterList.Any() ? "" : $"{Environment.NewLine}WHERE {string.Join($"{Environment.NewLine} AND ", filterList)} ") + $"{Environment.NewLine}ORDER BY {sortField.DatabaseName} {sortDirection.GetDescription()} " + $"{Environment.NewLine}OFFSET {pageNumber} * {pageSize} LIMIT {pageSize};"; List <_GenericEntity> result = uow._DynamicRepository.Sql(query) .Select(e => { var ent = new _GenericEntity() { EntityId = _entityId }; ent.Fields = e .Select(f => { var fieldId = Int32.Parse(f.Key.Replace("f_", "")); var field = fields.FirstOrDefault(x => x.Id == fieldId); return(new _GenericEntityField() { FieldId = fieldId, _FieldTypeId = field._FieldTypeId, Value = f.Value as string }); }) .ToList(); return(ent); }) .ToList(); return(result); } }
public int SaveEntity(_GenericEntity genericEntity, int userId) { Argument.Require(genericEntity != null, "Сущность пустая."); Argument.Require(userId > 0, "Идентификатор пользователя пустой."); Argument.Require(genericEntity.EntityId > 0, "Идентификатор сущности пустой."); using (var uow = this.CreateAdminUnitOfWork()) { _Entity entity = uow._EntityRepository.GetById(genericEntity.EntityId); Argument.Require(entity != null, "Сущность не найдена."); List <_Field> fields = uow._FieldRepository.Query(entityId: entity.Id); _Field identityField = fields.FirstOrDefault(f => f.IsIdentity); Argument.Require(identityField != null, "В сущности не найдено поле-идентификатор."); var identityFieldWithValue = genericEntity.Fields.FirstOrDefault(e => e.FieldId == identityField.Id); Argument.Require(identityFieldWithValue != null, "Не найдено значение поля-идентификатора в сохраняемых данных."); bool isEdit = !string.IsNullOrWhiteSpace(identityFieldWithValue.Value) && Int32.TryParse(identityFieldWithValue.Value, out int id) && id != 0; if (isEdit) { _GenericEntity existingEntityInstance = this.GetEntitiesList( _entityId: entity.Id, filters: new List <_GenericEntityFieldFilter>() { new _GenericEntityFieldFilter() { _FieldId = identityField.Id, Value = identityFieldWithValue.Value } }, pageSize: 1).FirstOrDefault(); Argument.Require(existingEntityInstance != null, "Обновляемая сущность не найдена."); } Dictionary <int, string> fieldSqlValues = new Dictionary <int, string>(); foreach (var field in fields) { _GenericEntityField fieldWithValue = genericEntity.Fields.FirstOrDefault(x => x.FieldId == field.Id); object deserializedValue = _DeserializeField(fieldWithValue?.Value, field._FieldTypeId); string sqlValue = _ToSqlField(deserializedValue, field._FieldTypeId); fieldSqlValues[field.Id] = sqlValue; } string fieldNames = string.Join($"{Environment.NewLine}, ", fields.Where(f => !f.IsIdentity).Select(f => f.DatabaseName)); string fieldValues = string.Join($"{Environment.NewLine}, ", fields.Where(f => !f.IsIdentity).Select(f => fieldSqlValues[f.Id])); string upsertQuery = null; if (isEdit) { upsertQuery = $"UPDATE {entity.DatabaseScheme}.\"{entity.DatabaseName}\" " + "SET (" + $"{Environment.NewLine}{fieldNames}" + ")" + $"{Environment.NewLine}= ({fieldValues})" + $"{Environment.NewLine}WHERE {identityField.DatabaseName} = {fieldSqlValues[identityField.Id]};"; } else { upsertQuery = $"INSERT INTO {entity.DatabaseScheme}.\"{entity.DatabaseName}\" " + $"{Environment.NewLine}(" + $"{Environment.NewLine}{fieldNames}" + $"{Environment.NewLine}) VALUES (" + $"{Environment.NewLine}{fieldValues}" + $"{Environment.NewLine}) " + $"{Environment.NewLine}RETURNING {identityField.DatabaseName};"; } var result = uow._DynamicRepository.Sql(upsertQuery); var resultRow = result.FirstOrDefault(); if (resultRow == null || resultRow.Values.Count == 0) { return(0); } int newId = (result.FirstOrDefault().Values.FirstOrDefault() as int?) ?? 0; return(newId); } }
public bool Merge <T>(_Entity entity) { entity.Code = entity.Code.ToUpper(); return(_db.Merge <T>(entity)); }