Entity Framework Core Tutorial 포함 & 포함
포함
Include
메소드는 조회 결과에 포함 할 관련 오브젝트를 지정합니다. 데이터베이스에서 일부 정보를 검색하는 데 사용할 수 있으며 관련 엔티티도 포함하고자합니다. 이제 세 개의 엔티티가 포함 된 간단한 모델이 있다고 가정 해 보겠습니다.
public class Customer { public int CustomerId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } public virtual List<Invoice> Invoices { get; set; } } public class Invoice { public int InvoiceId { get; set; } public DateTime Date { get; set; } public int CustomerId { get; set; } [ForeignKey("CustomerId")] public Customer Customer { get; set; } public List<InvoiceItem> Items { get; set; } } public class InvoiceItem { public int InvoiceItemId { get; set; } public int InvoiceId { get; set; } public string Code { get; set; } [ForeignKey("InvoiceId")] public virtual Invoice Invoice { get; set; } }
이제 모든 고객 및 관련 송장을 검색하려면 Include
메소드를 사용해야합니다.
using (var context = new MyContext()) { var customers = context.Customers .Include(c => c.Invoices) .ToList(); }
그런 다음 포함
Include
메소드는 오브젝트의 Lists에 대해서는 꽤 잘 작동하지만, 여러 레벨의 깊이가 필요한 경우에는 어떻게 될까요? 예를 들어 고객은 인보이스 목록을 포함하고 있으며 각 인보이스에는 항목 목록이 포함되어 있습니다.
EF Core에는 새로운 확장 메소드 인 ThenInclude ()가 있습니다. 관계를 통해 드릴 다운하여 ThenInclude 메서드를 사용하여 여러 수준의 관련 데이터를 포함 할 수 있습니다.
using (var context = new MyContext()) { var customers = context.Customers .Include(i => i.Invoices) .ThenInclude(it => it.Items) .ToList(); }