我正在为练习构建一个简单的API,如下所示:
我的学生,入学和课程模型是这样的:
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }
}
namespace.Models.School
{
public enum Grade
{
A, B, C, D, F
}
public class Enrollment
{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public Grade? Grade { get; set; }
public Course Course { get; set; }
public Student Student { get; set; }
}
}
public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }
}
我的DbContext是这样的:
public DbSet<Course> Courses { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Student> Students { get; set; }
我的控制器中有两种方法,如下所示:
[HttpGet]
public async Task<IEnumerable<Student>> GetAllSudents()
{
var students = await _context.Students.ToListAsync();
return (students);
}
[HttpGet("{id}")]
public async Task<IActionResult> GetSingleStudent(int id)
{
return Ok( await _context.Students
.Include(s => s.Enrollments)
.ThenInclude(e => e.Course)
.FirstOrDefaultAsync(m => m.ID == id));
}
现在,GetAllStudets()函数正常运行,Chrome和邮差中的所有学生,GetSingleStudent()也会在Chrome中连续加载并在控制台中出现此错误时带回单个学生结果:
36:1 GET http://localhost:49170/api/students/36 net::ERR_CONNECTION_RESET
在Postman中,它只是说:
Could not get any response
There was an error connecting to http://localhost:49170/api/students/36
我的问题是,如何摆脱这个错误并改进这个Api?
答案 0 :(得分:1)
我发现我的学生表有一个注册集合,在内部注册我有课程,在课程内我再次注册。 所以它导致了自我引用循环。为了解决这个问题,我必须在域模型之上创建Resources类,这样我的StudentResource看起来就像我的域模型一样:
public class StudentResource
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public ICollection<EnrollmentResource> Enrollments { get; set; }
}
但我必须更改EnrollmentResource类,该类不应该包含对学生和课程的反向引用。
public class EnrollmentResource
{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public Grade? Grade { get; set; }
}
在我的MappingProfile.cs类中,我将它们映射为:
CreateMap<Student, StudentResource>();
CreateMap<Enrollment, EnrollmentResource>();
最后我不得不改变GetSingleStudent(int id)方法类型的返回,如下所示:
return Ok(_mapper.Map<Student, StudentResource>(singleStudent));
错误不正确。