首页 > 解决方案 > 无法在 EF asp.net 核心中使用一个插入查询添加多行

问题描述

这是我知道的重复问题,很抱歉,但没有任何效果。我需要使用 foreach 语句将许多行添加到一个表中。

这是我的代码:

foreach (var ques in questions)
{
    await _db.Question.AddAsync(ques);
    await _db.SaveChangesAsync();
}

为每次插入添加新对象

foreach (var ques in questions)
{
    Question temp = new Question();
    temp.QuestionText = ques.QuestionText;
    temp.TypeId = ques.TypeId;
    await _db.Question.AddAsync(temp);
    await _db.SaveChangesAsync();
}

添加范围

List<Question> result = new List<Question>();
foreach (var ques in questions)
{
    Question temp = new Question();
    temp.QuestionText = ques.QuestionText;
    temp.TypeId = ques.TypeId;
    result.Add(temp);
}
_db.Question.AddRange(result);
_db.SaveChanges();

我也尝试不使用 Async 并尝试手动添加 id,但没有任何效果。ID 肯定是 AutoIncremental。

编辑:问题类:

    public partial class Question
    {
        public int IdQuestions { get; set; }
        public string QuestionText { get; set; }
        public int? TypeId { get; set; }
        public int? QuestionairId { get; set; }

        public virtual Questionnaire Questionair { get; set; }
        public virtual Questiontype Type { get; set; }
    }

json:

[
{
    "QuestionText": "How you doin'??",
    "TypeId": 1,
    "QuestionairId": 1
},
{
    "QuestionText": "Whaaaaaaaat??",
    "TypeId": 1,
    "QuestionairId": 1
}
]

标签: c#mysqlasp.netasp.net-coreentity-framework-core

解决方案


推荐阅读