Пример #1
0
        private async Task <int> ImportFromJsonFile(IFormFile file)
        {
            try
            {
                using (var stream = file.OpenReadStream())
                {
                    var buffer = new byte[file.Length];
                    await stream.ReadAsync(buffer, 0, buffer.Length);

                    var json = Encoding.UTF8.GetString(buffer);
                    var list = JsonConvert.DeserializeObject <List <QandA> >(json);

                    var answers = new List <QandA>();
                    if (list != null)
                    {
                        foreach (var item in list)
                        {
                            if (await ValidImportData(item.Intent, item.Answer))
                            {
                                answers.Add(new QandA {
                                    Id = Guid.NewGuid(), Answer = item.Answer, Intent = item.Intent
                                });
                            }
                        }
                        await _answerService.AddRangeAsync(answers);

                        await _answerService.SaveChangesAsync();
                    }
                    return(answers.Count);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError($"从json导入数据失败:{ex.Message}");
                throw ex;
            }
        }