[ASP.Net Core] Entity Framework Core 2 - LINQ ( Include , ThenInclude )
SQL 쿼리문에서 Join 문과 같이 관계가 연결되있는 부분을 LINQ 의 Include 와 ThenInclude 를 통하여 불러올수 있는데, 이에 좋은 포스팅 글이 있어서 소개한다.
https://entityframeworkcore.com/querying-data-include-theninclude
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
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; }
}
Controller 에서
var customer = db.Customers.Single(c => c.CustomerId == cid);
var invoices = db.Customers.Include(c => c.Invoices).ThenInclude(c2 => c2.InvoiceItems)
.Where(c3 => c3.CustomerId == cid).ToList();
|
cs |
https://learn.microsoft.com/ko-kr/ef/core/querying/related-data/eager
https://learn.microsoft.com/ko-kr/ef/core/modeling/entity-types?tabs=data-annotations
[ MS 의 아주 좋은 EF 예제 ] - 다대다 관계 등 다양한 내용 수록
https://learn.microsoft.com/ko-kr/aspnet/core/data/ef-mvc/complex-data-model?view=aspnetcore-6.0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
using (var context = new BloggingContext())
{
var blogs = context.Blogs
.Include(blog => blog.Posts)
.Include(blog => blog.Owner)
.ToList();
}
using (var context = new BloggingContext())
{
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ThenInclude(post => post.Author)
.ThenInclude(author => author.Photo)
.Include(blog => blog.Owner)
.ThenInclude(owner => owner.Photo)
.ToList();
}
|
cs |
https://www.tutorialsteacher.com/linq/what-is-linq
https://www.tutorialsteacher.com/linq/linq-method-syntax
https://www.tutorialsteacher.com/linq/linq-lambda-expression
[ DTO 관련 내용 설명 ]
https://www.telerik.com/blogs/dotnet-basics-dto-data-transfer-object
[ EF Core Performance Optimization Challenge ]
https://www.youtube.com/watch?v=jSiGyPHqnpY
https://github.com/StefanTheCode/OptimizeMePlease
참고 : https://dleunji.tistory.com/45?category=999005
참고 : https://learn.microsoft.com/ko-kr/aspnet/core/data/ef-mvc/read-related-data?view=aspnetcore-6.0
참고 : https://github.com/dotnet/AspNetCore.Docs/tree/main/aspnetcore/data/ef-mvc/intro/samples/cu-final
ASP.NetCore 깃허브 자료실
https://github.com/dotnet/AspNetCore.Docs