简体   繁体   中英

How to insert multiple entities that have same value for navigation property?

I have POCO like these:

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }
    public Level Level { get; set; }
}

public class Level
{
    public int LevelId { get; set; }
    public string Name { get; set; }
    public ICollection<Student> Students { get; set; }


}

And here is how I'm saving all students in a single level:

public void InsertAllFirstLevelStudents(List<Student> students)
{
    // Here all students belong to the same level
    var level = Utils.GetFirstLevel();

    students.ForEach(s => s.Level = level);
    context.Students.AddRange(students);
    context.SaveChanges();
}

But when saving, I get this error:

entity object cannot be referenced by multiple instances of IEntityChangeTracker

When I fetch the same level individually like: context.Levels.FirstOrDefault(l=> l.Name == "First"); , there is no problem, but of course, it then executes separate db queries to which is what I'm trying to avoid.

What can be done for this ?

public class Student
{
    public int StudentId { get; set; }
    public LevelId {get; set;}

    public string Name { get; set; }
    [ForeignKey("LevelId")]
    public Level Level { get; set; }
}

and then

students.ForEach(s => s.LevelId = level.LevelId);

You can just add the student to the Students collection of the level.

// Here all students belong to the same level
var level = Utils.GetFirstLevel();

foreach (var student in students) {
    level.Students.Add(student);
}
context.Students.AddRange(students); // Probably not necessary
context.SaveChanges();

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