我是 API 和 Blazor 的新手,我正在尝试遵循此示例 (https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/crud?view=aspnetcore-5.0)
您可以在下面看到我的模型和代码。
型号:
public class Student {
public int StudentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime EnrollmentDate { get; set; }
[JsonIgnore]
public virtual ICollection<Enrollment> Enrollments { get; set;}
}
API 控制器:
[HttpGet]
[Route("{id:int}")]
public async Task<ActionResult<Student>> GetStudent(int id)
{
try
{
var result = await context.Students
.Include(s => s.Enrollments)
.ThenInclude(e => e.Course)
.AsNoTracking()
.FirstOrDefaultAsync(m => m.StudentId == id);
//var result = await context.Students
// .Where(s => s.StudentId == id)
// .Select(s => new
// {
// Student = s,
// Enrollment = s.Enrollments
// })
// .FirstOrDefaultAsync();
if (result == null)
{
return NotFound();
}
return Ok(result);
}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Error receiving data from database");
}
}
Blazor 服务器中的学生模型
public class Student
{
public int StudentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime EnrollmentDate { get; set; }
[JsonIgnore]
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
我的 Blazor 学生群:
public class StudentDetailsBase : ComponentBase
{
[Inject]
public IEnrollmentService EnrollmentService { get; set; }
[Inject]
public IStudentService StudentService { get; set; }
public Student Student { get; set; }
public List<Enrollment> Enrollments { get; set; }
//public ICollection<Student> Student { get; set; }
[Parameter]
public string Id { get; set; }
protected override async Task OnInitializedAsync()
{
Id = Id ?? "1";
Student = await StudentService.GetStudent(int.Parse(Id));
Enrollments = (await EnrollmentService.GetEnrollmentBySID(int.Parse(Id))).ToList();
//Student = (await StudentService.GetStudent(int.Parse(Id))).ToList();
}
}
还有我的学生显示页面:
@if (Student == null)
{
<p>Loading ...</p>
}
else
{
<div>
<table class="table">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Enrollment Date</th>
<th>All enrollments</th>
</tr>
</thead>
<tbody>
<tr>
<td>@Student.FirstName</td>
<td>@Student.LastName</td>
<td>@Student.EnrollmentDate</td>
@foreach (var i in Student.Enrollments)
{
<td>@i.Course.Title</td>
<td>@i.Grade</td>
}
</tr>
</tbody>
</table>
</div>
}
我试图用谷歌搜索这个问题,但我不知道我做错了什么。 我的 Student.Enrollments 始终为 null。 这会导致我的 Blazor 服务器抛出错误。
当我使用 Postman 测试我的 API 时,它工作正常。
希望有人能指出我如何解决这个问题的正确方向。
谢谢。 亲切的问候。