简体   繁体   English

使用foreach访问列表

[英]using foreach to access a list

I am using a foreach loop to access the values of objects(of type Meal) stored in a list. 我正在使用一个foreach循环来访问存储在列表中的(Meal类型的)对象的值。 Then I am calling a database query to save these values into the database . 然后,我调用数据库查询以将这些值保存到数据库中。

This is the code I'm using : 这是我正在使用的代码:

foreach (Meal ml in mVals)
            {
                    mID = ml.mealID;
                    MessageBox.Show(Convert.ToString(mID));
                    string oString2 = " INSERT into [dbo].[OrderMeal] (orderId,mealId,quantity) " + " VALUES ('" + orderId + "','" + mID + "','" + Convert.ToInt32(quant.Text) + "') ;";
                    SqlCommand oCmd2 = new SqlCommand(oString2, myConnection);
                    oCmd2.ExecuteNonQuery();

            }

However, this only works for the last value in the list. 但是,这仅适用于列表中的最后一个值。 The next loop iteration seems to be doing the same function, thereby saving the same record, giving an 下一个循环迭代似乎在执行相同的功能,从而保存了相同的记录,

error of violating the primary key constraint . 违反主键约束的错误。

Is there some error in the way I am looping through the List? 我遍历列表的方式是否存在一些错误?

What the structure of OrderMeal table? OrderMeal表的结构是什么? Probably you have primary key in your table, and you need to vetify that you don't duplicate him. 可能您的表中有主键,您需要验证您没有重复他。

try to enter the value in the list from the sql management. 尝试在sql管理列表中输入值。 verify that you don't have special characters in each item in the list( like comma and Apostrophe). 确认列表中的每个项目中都没有特殊字符(例如逗号和Apostrophe)。

I think you can concatenate a set of insert statement and then ExcuteNonQuery for better performance. 我认为您可以连接一组插入语句,然后连接ExcuteNonQuery以获得更好的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM