简体   繁体   English

使用linq-to-sql更新记录列表

[英]updating a list of records with linq-to-sql

I have a table that has 2 columns: FruitID, FruitSize. 我有一个有2列的表:FruitID,FruitSize。 I want to write a query that takes in a list of FruitIDs and a FruitSize and that sets the new FruitSize for all the fruits. 我想编写一个查询,其中包含FruitIDs和FruitSize的列表,并为所有水果设置新的FruitSize。

This is what I have so far: 这是我到目前为止:

public void ChangeFruitSizes(List<long> TheFruitIDs, long NewFruitSize)
{
   using (SomeDC MyDC = new SomeDC())
   {
      var TheFruits = (from f in MyDC.Fruits
                       where TheFruitIDs.Contains(f.FruitID)
                       select f).ToList();

      foreach (Fruits f in TheFruits)
      {
          f.FruitSize = NewFruitSize;
      }

      MyDC.SubmitChanges();

   }
}

It's currently not bugging but the fields in the database aren't updated. 它目前没有窃听,但数据库中的字段未更新。 Thanks for your suggestions. 谢谢你的建议。

To write this in more concise way, you can try ForEach() in list like below: 要以更简洁的方式编写它,您可以在列表中尝试ForEach() ,如下所示:

using (SomeDC MyDC = new SomeDC())
{
    (from f in MyDC.Fruits
               where TheFruitIDs.Contains(f.FruitID)
               select f).ToList().ForEach(F => F.FruitSize = NewFruitSize);

    MyDC.SubmitChanges();

}

Just looking at the code everything is correct. 只看代码一切都是正确的。 Probably the error is at what is not shown: The model. 可能错误在于未显示的内容:模型。 I suspect you don't have a primary key defined. 我怀疑你没有定义主键。 Define a primary key on the ID field and re-create the model (remove the table from the designer and add it back). 在ID字段上定义主键并重新创建模型(从设计器中删除表并将其添加回来)。

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

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