InvalidOperationException:Sequence包含多个元素 - SingleOrDefault()

时间:2015-12-10 21:28:38

标签: c# asp.net linq linq-to-entities invalidoperationexception

using (var db = new ABC())
{

for (int column = rangeClass2.Start.Column; column <= rangeClass2.End.Column; column++)
{
   var classValue = censusSheet.Cells[row, column].Value;
   var description = censusSheet.Cells[3, 27].Value;
 lifeReductionByData.Add(classASheet.getClassFromExcelPivotedValuedreductionBy<tbl_Life_Reduction_By>(25, 1, 33, 4, lifeReductionByClassMapper).FirstOrDefault());
 for (int i = 0; i < lifeReductionByData.Count; i++)
 {
     lifeReductionByData[i].Class = classesValue[x];
     lifeReductionByData[i].UUID = censusSheet.GetValue(25, 27).ToString();
 }
}
var entry = new tbl_Life_Master() { UUID = uuidVar };
entry.tbl_Life_Reduction_By = lifeReductionByData;
context.tbl_Life_Master.Add(entry);
context.SaveChanges();
}

通过搜索Stack Overflow,我很清楚FirstOrDefault()是避免这种执行的最佳方法。但是,如果我想在我的列表中添加多个记录,那么解决方案是什么?由于“ getClassFromExcelPivotedValuedreductionBy ”,此处返回3条记录。请帮帮我。

1 个答案:

答案 0 :(得分:0)

  

但如果我想在我的列表中添加多个记录,那么解决方案是什么?

您的意思是您要添加所有结果?假设lifeReductionByData是适当类型的List<T>,您只需使用List<T>.AddRange

var query = classASheet.getClassFromExcelPivotedValuedreductionBy<tbl_Life_Reduction_By>(25, 1, 33, 4, lifeReductionByClassMapper);
lifeReductionByData.AddRange(query);
foreach (var item in lifeReductionByData)
{
    item.Class = classesValue[x];
    item.UUID = censusSheet.GetValue(25, 27).ToString();
}

请注意此处使用foreach而不是索引。现在,如果lifeReductionByData在此代码之前实际上是空的,并且之后您不需要它,那么您可以迭代查询本身:

var query = classASheet.getClassFromExcelPivotedValuedreductionBy<tbl_Life_Reduction_By>(25, 1, 33, 4, lifeReductionByClassMapper);
foreach (var item in query)
{
    item.Class = classesValue[x];
    item.UUID = censusSheet.GetValue(25, 27).ToString();
}

如果之后需要列表,但事先是空的,那么我会使用:

var query = classASheet.getClassFromExcelPivotedValuedreductionBy<tbl_Life_Reduction_By>(25, 1, 33, 4, lifeReductionByClassMapper);
var list = query.ToList();
foreach (var item in list)
{
    item.Class = classesValue[x];
    item.UUID = censusSheet.GetValue(25, 27).ToString();
}

接下来,我将getClassFromExcelPivotedValuedreductionBy重命名为a)更简洁; b)遵循.NET命名约定。