Esempio n. 1
0
        public async Task <ResponseBase> BatchInsertEntitiesAsync <TEntity>(IEnumerable <TranslatedRequest> requests, Type type, string idPropName)
            where TEntity : BaseTranslateModel
        {
            var response = new ResponseBase();
            EntityEntry <TEntity>  insertedContributor = null;
            EntityEntry <Langtext> insertedLangText    = null;

            foreach (var request in requests)
            {
                var    langId = _context.Lang.FirstOrDefault(l => l.LangCode == request.LangCode.GetDescription())?.LangId;
                string suffix = string.Empty;

                if (!SuffixToPropertyMap.TryGetValue(idPropName, out suffix))
                {
                    response.ErrorMessage = $"BatchInsertOrUpdateEntitiesAsync:: Provided argument idPropName -> ${idPropName} is invalid";
                }

                //RECORD CREATION RULES
                var langTextCode = $"{request.Name.ToUpperInvariant().Replace(" ", "_")}_{suffix}";

                if (_context.GetDbSet <TEntity>().FirstOrDefault(c => c.LangTextCode == langTextCode) != null)
                {
                    throw new Exception($"ERROR: entity of type {type} with that id already exists.");
                }

                //Add to TEntity Table if not exists
                if (_context.ChangeTracker.Entries <TEntity>().FirstOrDefault(m => m.Entity.LangTextCode == langTextCode) == null)
                {
                    var instantiatedObject = Activator.CreateInstance(type, langTextCode) as TEntity;

                    insertedContributor = await _context.GetDbSet <TEntity>().AddAsync(instantiatedObject);
                }

                var entityId = insertedContributor.Member(idPropName).CurrentValue;

                //Add to Langtext based on request
                var lngTextEntry = new Langtext
                {
                    TextCode        = langTextCode,
                    TextName        = request.Name,
                    TextTitle       = request.Title,
                    TextDescription = request.Description,
                    LangId          = langId.Value,
                };

                lngTextEntry.GetType().GetProperty(idPropName).SetValue(lngTextEntry, (int?)entityId);

                insertedLangText = await _context.Langtext.AddAsync(lngTextEntry);
            }

            response.RowsAffected = await _context.SaveChangesAsync();

            return(await Task.FromResult(response));
        }