I got the following code:
//getting skills from DB
var skills = this.db.HumanSkills.Where(r => r.HumanId == model.Id).Include(x => x.Skill).ToList();
for (int i = 0; i < model.Skills.Count; i ) //iterating over the list. Boundary set to i < model.Skills.Count this is number of elements in my viewmodel (model.Skills) using which I am going to update Name property of my DB elements.
{
if (skills[i] != null) //index out of range here. Why?
{
//here I update DB skill names using model skill names
skills[i].Skill.Name = model.Skills[i].Skill.Name;
}
else //here I create new Skill for every element of the DB skill list that doesn't exist
{
var newSkill = new HumanSkill { Skill = model.Skills[i].Skill, Human = currentHuman };
this.db.Add(newSkill);
this.db.SaveChanges(); //yes, I know it's not a good practice to execute it each time, but otherwise rows in my HumanSkills table are not sorted.
}
}
On line:
if (skills[i] != null) //index out of range here. Why?
I am getting index out of range, even though I use !=null
CodePudding user response:
It seems to me that var skills is a different object than model.Skills
CodePudding user response:
"var skills" and "model.Skills" are 2 different variables. There are of the same type, but it's 2 differents objects!
In my opinion it's simpler like that :
IEnumerable<Skill> skillsList = this.db.HumanSkills.Where(r => r.HumanId == model.Id).Include(x => x.Skill).ToList();
foreach (Skill s in skillsList)
{
// your logic... or debug.print for check how many items are get from the db
}
But I don't understand why you use the "model.Skills" variable here...
Regards.