在Controller Action中返回ICollection缺少数据

时间:2016-10-11 15:44:32

标签: javascript c# angularjs angular asp.net-core

我正在关注上下文here的Microsoft教程。我遇到的问题是,当我返回我的学生对象时,作为ICollection称为Enrollments,ICollection的计数为3(我调试它并且值都是正确的),但当我打印出对象时控制台计数只显示1.任何想法可能导致返回数据丢失数据?这可能是Anuglar2读取ICollection的方式吗?

StudentController.cs

public async Task<IActionResult> getDetails([FromBody] int id) {
    var student = await context.Students.Include(s => s.Enrollments)
        .ThenInclude(e => e.Course)
        .AsNoTracking()
        .SingleOrDefaultAsync(m => m.ID == id);
    if (student == null) {
        return NotFound();
    }
/*
student = 
EnrollmentDate:{9/1/05 12:00:00 AM} [System.DateTime]
Enrollments:Count = 3 [System.Collections.Generic.ICollection<ContosoUniversity.Models.Enrollment> {System.Collections.Generic.HashSet<ContosoUniversity.Models.Enrollment>}]
FirstMidName:"Carson" [string]
ID:1 [int]
LastName:"Alexander" [string]
*/
return Json(student); 

}

视图

getDetails(id:number){
    let headers = new Headers({ 'Content-Type': 'application/json' });
    this.http.post('/api/Student/getDetails', id, {headers:headers}).subscribe(result => {
        console.log(result.json()); 
    });
} 

控制台

Object { id: 1, lastName: "Alexander", firstMidName: "Carson", enrollmentDate: "2005-09-01T00:00:00", enrollments: Array[1] }

SchoolContext.cs

public class SchoolContext : DbContext
{
    public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
    {
    }

    public DbSet<Course> Courses { get; set; }
    public DbSet<Enrollment> Enrollments { get; set; }
    public DbSet<Student> Students { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Course>().ToTable("Course");
        modelBuilder.Entity<Enrollment>().ToTable("Enrollment");
        modelBuilder.Entity<Student>().ToTable("Student");
    }
}

Soultion Startup.cs

    // Add framework services
    services.AddMvc().AddJsonOptions(options => {
        options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
    });

0 个答案:

没有答案