Aja*_*y P 7 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;
}
Run Code Online (Sandbox Code Playgroud)
当我将记录添加到列表对象即fadd时,记录将被覆盖AllList的最后一个值
Ada*_*dam 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();
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,你不应该保留一个你一直访问的数据上下文; 最好在using语句中本地创建一个,以正确处理数据库断开连接.
Yog*_*pta 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20817 次 |
| 最近记录: |