Beispiel #1
0
        private async Task <KerykeionDbResult> SetForeignKeyAsync(object entity, string formValue, string propertyName)
        {
            var foreignKey = FindEntityTypeByClrType(entity.GetType()).GetForeignKeys().FirstOrDefault(fk => fk.GetDefaultName().Contains(propertyName, StringComparison.OrdinalIgnoreCase));

            if (foreignKey == null)
            {
                return(null);
            }

            if (string.IsNullOrEmpty(formValue?.Trim()))
            {
                if (foreignKey.IsRequired)
                {
                    return(KerykeionDbResult.Fail(new KerykeionDbError {
                        Message = _translationsService.TranslateErrorByDescriber(ErrorDescriberConstants.RequiredField, $"The field '{propertyName}' is required.", propertyName)
                    }));
                }

                Context.Entry(entity).Property(propertyName).CurrentValue = null;
                return(null);
            }

            if (!Guid.TryParse(formValue, out _))
            {
                return(KerykeionDbResult.Fail(new KerykeionDbError {
                    Message = _translationsService.TranslateErrorByDescriber(ErrorDescriberConstants.NotValidGuid, $"Please provide a valid GUID for the property '{propertyName}'.", propertyName)
                }));
            }

            var foreignPrincipalEntityType = foreignKey?.PrincipalEntityType?.ClrType;

            if (foreignPrincipalEntityType == null)
            {
                return(null);
            }

            var foreignEntity = await Context.FindAsync(foreignPrincipalEntityType, Guid.Parse(formValue));

            if (foreignEntity == null)
            {
                return(KerykeionDbResult.Fail(new KerykeionDbError {
                    Message = _translationsService.TranslateErrorByDescriber(ErrorDescriberConstants.EntityNotExistsWithSpecifiedPriKey, $"There is no '{foreignPrincipalEntityType?.Name}' found in the database with '{formValue}' as primary key.", foreignPrincipalEntityType?.Name, formValue)
                }));
            }

            Context.Entry(entity).Property(propertyName).CurrentValue = Guid.Parse(formValue);

            return(KerykeionDbResult.Success());
        }
Beispiel #2
0
        private async Task <KerykeionDbResult> TrySaveChangesAsync(object entity = null)
        {
            try
            {
                await Context.SaveChangesAsync();

                return(KerykeionDbResult.Success(entity));
            }
            catch (Exception ex)
            {
                return(KerykeionDbResult.Fail(new KerykeionDbError
                {
                    Message = ex.InnerException.Message
                }));
            }
        }
Beispiel #3
0
        /// <summary>
        /// Sets Foreign Key property values to the specified Entity.
        /// </summary>
        /// <param name="entity">The Entity to set the foreign keys value to.</param>
        /// <param name="formForeignKeys">The form dictionary foreign keys and values.</param>
        /// <returns>
        /// The System.Threading.Tasks.Task that represents the asynchronous operation, containing the KerykeionDbResult of the operation.
        /// </returns>
        public async Task <KerykeionDbResult> SetForeignKeysAsync(object entity, IEnumerable <KeyValuePair <string, StringValues> > formForeignKeys)
        {
            foreach (var key in formForeignKeys)
            {
                var foreignKeyName = key.Key.Split("-").Last();

                var result = await SetForeignKeyAsync(entity, key.Value.ToString(), foreignKeyName);

                if (result == null)
                {
                    continue;
                }

                if (!result.Successfull)
                {
                    return(result);
                }
            }

            return(KerykeionDbResult.Success());
        }
Beispiel #4
0
        private async Task <KerykeionDbResult> SetPropertiesAsync(object entity, Dictionary <string, StringValues> formDict)
        {
            var entityType = FindEntityTypeByClrType(entity.GetType());
            List <KerykeionDbError> errors = new List <KerykeionDbError>();

            foreach (var prop in entityType.GetProperties())
            {
                var property = entityType.ClrType.GetProperty(prop.Name);
                if (property == null)
                {
                    if (formDict.ContainsKey(prop.Name))
                    {
                        var result = await SetForeignKeyAsync(entity, formDict[prop.Name].ToString(), prop.Name);

                        if (result == null)
                        {
                            continue;
                        }

                        if (!result.Successfull)
                        {
                            errors.Add(result.Errors.FirstOrDefault());
                        }
                    }

                    continue;
                }
                if (prop.Name.Equals(PropertyNameConstants.Id, StringComparison.OrdinalIgnoreCase) || prop.Name.Equals(PropertyNameConstants.DateTimeCreated, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                if (formDict.ContainsKey(prop.Name))
                {
                    if (prop.IsPrimaryKey())
                    {
                        if (Guid.TryParse(formDict[prop.Name], out _))
                        {
                            var navigation = entityType.GetNavigations().FirstOrDefault(n => prop.Name.Contains(n.Name, StringComparison.OrdinalIgnoreCase));
                            var targetType = navigation?.GetTargetType()?.ClrType;
                            if (targetType == null)
                            {
                                errors.Add(new KerykeionDbError {
                                    Message = _translationsService.TranslateErrorByDescriber(ErrorDescriberConstants.EntityNotExistsWithSpecifiedPriKey, $"There is no '{targetType?.Name}' found in the database with '{formDict[prop.Name]}' as primary key.", targetType?.Name, formDict[prop.Name])
                                });
                                continue;
                            }

                            var target = await Context.FindAsync(targetType, Guid.Parse(formDict[prop.Name]));

                            if (target == null)
                            {
                                errors.Add(new KerykeionDbError {
                                    Message = _translationsService.TranslateErrorByDescriber(ErrorDescriberConstants.EntityNotExistsWithSpecifiedPriKey, $"There is no '{targetType?.Name}' found in the database with '{formDict[prop.Name]}' as primary key.", targetType?.Name, formDict[prop.Name])
                                });
                                continue;
                            }

                            property.SetValue(entity, Guid.Parse(formDict[prop.Name]));
                            continue;
                        }

                        errors.Add(new KerykeionDbError
                        {
                            Message = _translationsService.TranslateErrorByDescriber(ErrorDescriberConstants.NotValidGuid, $"Please provide a valid GUID for the property '{prop.Name}'.", prop.Name)
                        });

                        continue;
                    }

                    if (prop.IsForeignKey())
                    {
                        var result = await SetForeignKeyAsync(entity, formDict[prop.Name].ToString(), prop.Name);

                        if (result == null)
                        {
                            continue;
                        }

                        if (!result.Successfull)
                        {
                            errors.Add(result.Errors.FirstOrDefault());
                        }

                        continue;
                    }

                    if (string.IsNullOrEmpty(formDict[prop.Name]))
                    {
                        continue;
                    }

                    if (int.TryParse(formDict[prop.Name], out _))
                    {
                        property.SetValue(entity, int.Parse(formDict[prop.Name]));
                        continue;
                    }

                    if (bool.TryParse(formDict[prop.Name], out _))
                    {
                        property.SetValue(entity, bool.Parse(formDict[prop.Name]));
                        continue;
                    }

                    if (DateTime.TryParse(formDict[prop.Name], out _))
                    {
                        property.SetValue(entity, DateTime.Parse(formDict[prop.Name]));
                        continue;
                    }

                    if (TimeSpan.TryParse(formDict[prop.Name], out _))
                    {
                        property.SetValue(entity, TimeSpan.Parse(formDict[prop.Name]));
                        continue;
                    }

                    if (float.TryParse(formDict[prop.Name], out _))
                    {
                        property.SetValue(entity, float.Parse(formDict[prop.Name]));
                        continue;
                    }

                    if (double.TryParse(formDict[prop.Name], out _))
                    {
                        property.SetValue(entity, double.Parse(formDict[prop.Name]));
                        continue;
                    }

                    if (decimal.TryParse(formDict[prop.Name], out _))
                    {
                        property.SetValue(entity, decimal.Parse(formDict[prop.Name]));
                        continue;
                    }

                    property.SetValue(entity, formDict[prop.Name].ToString());
                }
            }

            if (errors.Count > 0)
            {
                return(KerykeionDbResult.Fail(errors.ToArray()));
            }

            return(KerykeionDbResult.Success());
        }