C# EF Core 3和Automapper的跟踪问题

C# EF Core 3和Automapper的跟踪问题,c#,automapper,ef-core-3.0,ef-core-3.1,C#,Automapper,Ef Core 3.0,Ef Core 3.1,我在使用从DTO映射的实体列表时遇到问题。此代码与早期版本的EF Core一起使用。GitHub上有一个关于此的问题- .AttachRange()引发错误: The instance of entity type 'School' cannot be tracked because another instance with the same key value for {'SchoolId'} is already being tracked. When attaching existing

我在使用从DTO映射的实体列表时遇到问题。此代码与早期版本的EF Core一起使用。GitHub上有一个关于此的问题-

.AttachRange()
引发错误:

The instance of entity type 'School' cannot be tracked because another instance with the same key value for {'SchoolId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
我知道如何修复这个示例,但是如果您有很多FK属性,例如一个实体列表,这些实体也有很多FK属性,那么这将很困难

有人知道如何正确地做到这一点吗

公立学校
{
公共int SchoolId{get;set;}
公共字符串名称{get;set;}
}
公立班学生
{
公共int StudentId{get;set;}
公共字符串名{get;set;}
公共字符串LastName{get;set;}
公立学校{get;set;}
}
var studentsDtos=新列表
{
新生
{
FirstName=“FirstName 1”,
LastName=“LastName 1”,
学校=新学校
{
学号=1
}
},
新生
{
FirstName=“FirstName 2”,
LastName=“LastName 2”,
学校=新学校
{
学号=1
}
}
};
var students=mapper.Map(studentsDtos);
db.Students.AttachRange(学生);
db.SaveChanges();
public class School
{
    public int SchoolId { get; set; }

    public string Name { get; set; }
}

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

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public School School { get; set; }
}



var studentsDtos = new List<StudentDTO>
                {
                    new StudentDTO
                    {
                        FirstName = "FirstName 1",
                        LastName = "LastName 1",
                        School = new SchoolDTO
                        {
                            SchoolId = 1
                        }
                    },
                    new StudentDTO
                    {
                        FirstName = "FirstName 2",
                        LastName = "LastName 2",
                        School = new SchoolDTO
                        {
                            SchoolId = 1
                        }
                    }
                };

                var students = mapper.Map<List<Student>>(studentsDtos);

                db.Students.AttachRange(students);

                db.SaveChanges();