使用Linq-to-SQL添加多个记录 [英] Add Multiple record using Linq-to-SQL

查看:108
本文介绍了使用Linq-to-SQL添加多个记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

推荐答案

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

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).

当您使用LINQ(为清楚起见,更名为方法)时,它变得更加有趣:

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

顺便说一句,您不应该一直保持访问一个数据上下文. 最好在内部创建一个 using语句,可以正确处理数据库断开连接.

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.

这篇关于使用Linq-to-SQL添加多个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆