【问题标题】:Update dbEnitity columns values from List<MyClass> without usinf two foreach loops从 List<MyClass> 更新 idEntity 列值而不使用两个 foreach 循环
【发布时间】:2019-12-19 18:03:04
【问题描述】:

我有一个类 - PairedValues.cs,代码如下:

public class PairedValues
{
    public string FileName { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }

    public PairedValues(string val1, DateTime val2, DateTime val3)
    {
        FileName = val1;
        StartTime = val2;
        EndTime = val3;
    }

    public PairedValues() { }
}

在我的其他方法中,我将文件名、开始时间和结束时间添加到列表中:

pairedValues.Add(new PairedValues(name, startTime, endTime));

现在,我有一个数据库,其中包含类似的列,例如 name、startTime、EndTime,我需要从pairedValues 更新此表,所以我正在遍历pairedValues 列表并尝试执行以下操作:

 foreach (var val in pairedValues)
 {           
     listOfFiles = GetListOfFiles()
         .Where(e => e.fileName == val.FileName)
         .ToList();
 }

我想从pairedValues 更新listofFiles 中每一列的值,我可以使用另一个foreach 来做到这一点,但如何避免呢?任何建议将不胜感激。

保存到数据库代码如下:

  public void SaveDetails(List<MyDbTable> listOfFiles)
    {
        _Entity.MyTable.AddRange(listOfFiles);

        try
        {
            _Entity.SaveChanges();
        }
        catch (DbUpdateException ex)
        {
            Console.WriteLine(ex);
        }
    }

【问题讨论】:

  • 为什么问题的中心代码(假定的第二个 for 循环)从问题中丢失?

标签: c# asp.net .net list entity-framework


【解决方案1】:

如果我理解正确

您有一个pairedValues 列表,并且对于每个配对值文件名GetListOfFiles 方法可能会返回一个或多个MyTable 类型的记录

在这种情况下,您需要使用嵌套循环,或者如果您愿意,可以使用 Linq

1-嵌套循环

 foreach (var val in pairedValues)
 {           
        foreach(var file in GetListOfFiles().Where(x=>x.fileName == 
         val.FileName).ToList())
         {
            //Create new record here (we don't know the property names)
            var newRecord = new MyTable();
            newRecord.FileName = file.Filename // or whater 

             //TODO Now add the new record to 
              _Entity.MyTable.Add(newRecord);
         }

 }
_Entity.SaveChanges();  // save outside the loop to reduce the database roundtrips..

2-Linq

pairedValues.forech(x=> {
    x.GetListOfFiles()
     .Where(e => e.fileName == val.FileName)
     .ToList().foreach(y=> {
          //Create new record here (we don't know the property names)
          var newRecord = new MyTable();
          newRecord.FileName = y.Filename // or whater 

         //TODO Now add the new record to 
          _Entity.MyTable.Add(newRecord);
      });
});

希望这会有所帮助!

P.S 我没有使用编译器编写代码,所以请原谅任何拼写错误..

【讨论】:

  • @Licentia- 感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-25
相关资源
最近更新 更多