Add Multiple record using Linq-to-SQL

2019-06-17 06:41发布

问题:

I want to add Multiple rows into Table using Linq to SQL

    public static FeedbackDatabaseDataContext context = new FeedbackDatabaseDataContext();
    public static bool Insert_Question_Answer(List<QuestionClass.Tabelfields> AllList)
    {
          Feedback f = new Feedback();
          List<Feedback> fadd = new List<Feedback>();
            for (int i = 0; i < AllList.Count; i++)
            {
                f.Email = AllList[i].Email;
                f.QuestionID = AllList[i].QuestionID;
                f.Answer = AllList[i].SelectedOption;
                fadd.Add(f);
            }
            context.Feedbacks.InsertAllOnSubmit(fadd);
            context.SubmitChanges();
        return true;            
    }

When I add records into list object i.e. fadd the record is overwrites with last value of AllList

回答1:

I'm late to the party, but I thought you might want to know that the for-loop is unnecessary. Better use foreach (you don't need the index).

It gets even more interesting when you use LINQ (renamed method for clarity):

public static void InsertFeedbacks(IEnumerable<QuestionClass.Tabelfields> allList)
{
    var fadd = from field in allList
               select new Feedback
                          {
                              Email = field.Email,
                              QuestionID = field.QuestionID,
                              Answer = field.SelectedOption
                          };
    context.Feedbacks.InsertAllOnSubmit(fadd);
    context.SubmitChanges();
}

By the way, you shouldn't keep one data context that you access all the time; it's better to create one locally, inside a using statement, that will properly handle the database disconnection.



回答2:

You should create object of Feedback in the scope of for loop, so change your method to :

public static bool Insert_Question_Answer(List<QuestionClass.Tabelfields> AllList)
{
      List<Feedback> fadd = new List<Feedback>();
        for (int i = 0; i < AllList.Count; i++)
        {
            Feedback f = new Feedback();
            f.Email = AllList[i].Email;
            f.QuestionID = AllList[i].QuestionID;
            f.Answer = AllList[i].SelectedOption;
            fadd.Add(f);
        }
        context.Feedbacks.InsertAllOnSubmit(fadd);
        context.SubmitChanges();
    return true;            
}