둘 이상의 관련 데이터베이스 테이블에서 데이터를 검색하고 Blazor 웹 애플리케이션에 표시하는 방법에 대해 설명합니다 아래 방식은 애플리케이션의 아키텍처, 복잡성 및 요구 사항에 따라 다릅니다.
다음 직원 세부 정보를 표시합니다.
- ID
- 이름
- 이메일
- 부서 이름
ID, 이름 및 이메일은 직원 데이터베이스 테이블 에서 가져오고 부서 이름은 부서 테이블 에서 가져옵니다 . 여기서 우리는 두 개의 데이터베이스 테이블로 작업하지만 동일한 기술을 사용하여 세 개 이상의 데이터베이스 테이블로 작업할 수 있습니다.
직원 클래스
Department 속성 은 DepartmentId 및 DepartmentName과 같은 직원 부서 데이터를 전달합니다.
public class Employee
{
public int EmployeeId { get; set; }
[Required]
[MinLength(2)]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string Email { get; set; }
public DateTime DateOfBrith { get; set; }
public Gender Gender { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
public string PhotoPath { get; set; }
}
EmployeeRepository
Employee 엔터티 에서 Department 와 같은 관련 엔터티 데이터를 포함하려면 Include() 메서드를 연결합니다 . 기술 데이터, 경험 데이터 등과 같은 추가 관련 엔터티를 포함하려는 경우 ThenInclude() 메서드를 연결합니다 .
public class EmployeeRepository : IEmployeeRepository
{
private readonly AppDbContext appDbContext;
public EmployeeRepository(AppDbContext appDbContext)
{
this.appDbContext = appDbContext;
}
public async Task<Employee> GetEmployee(int employeeId)
{
return await appDbContext.Employees
.Include(e => e.Department)
.FirstOrDefaultAsync(e => e.EmployeeId == employeeId);
}
}
EmployeeDetails 구성 요소
@page "/employeedetails/{id}"
@page "/employeedetails"
@inherits EmployeeDetailsBase
@if (Employee == null || Employee.Department == null)
{
<div class="spinner"></div>
}
else
{
<div class="row justify-content-center m-3">
<div class="col-sm-8">
<div class="card">
<div class="card-header">
<h1>@Employee.FirstName @Employee.LastName</h1>
</div>
<div class="card-body text-center">
<img class="card-img-top" src="@Employee.PhotoPath" />
<h4>Employee ID : @Employee.EmployeeId</h4>
<h4>Email : @Employee.Email</h4>
<h4>Department : @Employee.Department.DepartmentName</h4>
</div>
<div class="card-footer text-center">
<a href="/" class="btn btn-primary">Back</a>
<a href="#" class="btn btn-primary">Edit</a>
<a href="#" class="btn btn-danger">Delete</a>
</div>
</div>
</div>
</div>
}
다음 코드에서 처 null 검사가 필요합니다. 그렇지 않으면 보기가 해당 속성을 참조할 때 Employee 또는 Department 속성이 초기화되지 않으면 NullReferenceException 이 발생 합니다 .
@if (Employee == null || Employee.Department == null)
{
<div class="spinner"></div>
}