使用Linq-to-SQL添加多个记录

时间:2012-08-24 07:29:13

标签: c# sql-server-2008 linq-to-sql

我想使用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;            
    }

当我将记录添加到列表对象中,即 fadd 时,记录将被覆盖,其最后一个值为 AllList

2 个答案:

答案 0 :(得分:15)

我迟到了,但我想你可能想知道for循环是不必要的。更好地使用foreach(你不需要索引)。

使用LINQ(为了清晰起见重命名的方法),它会变得更有趣:

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();
}

顺便说一句,你不应该保留一个你一直访问的数据上下文; it's better to create one locally,在using语句中,将正确处理数据库断开连接。

答案 1 :(得分:12)

您应该在for循环的范围内创建Feedback的对象,因此请将您的方法更改为:

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;            
}