简体   繁体   中英

InvalidOperationException: Sequence contains more than one element - SingleOrDefault()

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();
}

By searching on Stack Overflow, it is clear to me that FirstOrDefault() is the best approach to avoid this execption. But if I want to add multiple records in my list once then what is the solution? As ' getClassFromExcelPivotedValuedreductionBy ' here is returning 3 records. Please help me out in this.

But if I want to add multiple records in my list once then what is the solution?

You mean you want to add all the results? Assuming that lifeReductionByData is a List<T> for the appropriate type, you can just use 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();
}

Note the use of foreach here instead of the index. Now, if lifeReductionByData was actually empty before this piece of code, and you don't need it afterwards, you can just iterate over the query itself:

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();
}

If you do need the list afterwards, but it was empty beforehand, then I'd use:

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();
}

Next up, I'd rename getClassFromExcelPivotedValuedreductionBy to a) be briefer; b) follow .NET naming conventions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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