Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Multiple record using Linq-to-SQL

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

like image 948
Ajay Avatar asked Aug 24 '12 07:08

Ajay


1 Answers

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.

like image 145
Adam Avatar answered Sep 17 '22 15:09

Adam