简体   繁体   中英

Index out of rage cannot be resolved [ASP.NET Core]

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? if (skills[i].= null) //index out of range here? Why?

I am getting index out of range, even though I use !=null

It seems to me that var skills is a different object than model.Skills

"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.

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