Lets say we have a class like this:
public class SampleClass
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public virtual ICollection<ScoreData> ScoreData{ get; set; }
}
And another class like this:
public class ScoreData
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id {get; set;}
public int subSectionScore {get; set;}
public int SampleClassID { get; set; }
public virtual SampleClass SampleClass { get; set; }
}
Why does this throw an object disposed exception and how can it be fixed?
internal static void CalculatesubSectionScores(ref List<SampleClass> sampleClassData)
{
foreach (var item in sampleClassData)
{
item.ScoreData= new List<ScoreData>();
/* code in second foreach accesses another objects item to
use for each sub sections calculations*/
foreach ()
{
var scoringData = new ScoreData();
var score = 0.0;
scoringData.subSectionScore = score;
item.ScoreData.Add(scoringData);
}
}
I've removed most of the logic from this class just to focus on the problem at hand.
Declare ScoreData
before adding to it
internal static void CalculatesubSectionScores(ref List<SampleClass> sampleClassData)
{
foreach (var item in sampleClassData)
{
item.ScoreData= new List<ScoreData>();
/* code in second foreach accesses another objects item to
use for each sub sections calculations*/
item.ScoreData = new List<ScoreData>(); // Add This Line
foreach ()
{
var scoringData = new ScoreData();
var score = 0.0;
scoringData.subSectionScore = score;
item.ScoreData.Add(scoringData);
}
}
}
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.