EF 6 - Lazy Loading
Lazy Loading trong Entity Framework
Lazy loading là gì?
Lazy loading trì hoãn việc tải các dữ liệu liên quan, cho đến khi bạn yêu cầu cụ thể. Lazy loading đối lập hoàn toàn với Eager loading.
Ví dụ, thực thể Student
chứa thực thể StudentAddress
. Trong lazy loading, Context trước tiên tải dữ liệu thực thể Student
từ cơ sở dữ liệu, sau đó nó sẽ tải thực thể StudentAddress
khi chúng ta truy cập thuộc tính StudentAddress
như dưới đây.
using (var ctx = new SchoolDBEntities())
{
//Loading students only
IList<Student> studList = ctx.Students.ToList<Student>();
Student std = studList[0];
//Loads Student address for particular Student only (seperate SQL query)
StudentAddress add = std.StudentAddress;
}
Mã được trình bày ở trên sẽ dẫn đến hai truy vấn SQL. Đầu tiên, nó sẽ lấy tất cả các sinh viên:
SELECT
[Extent1].[StudentID] AS [StudentID],
[Extent1].[StudentName] AS [StudentName],
[Extent1].[StandardId] AS [StandardId]
FROM [dbo].[Student] AS [Extent1]
Sau đó, nó sẽ gửi truy vấn sau đây khi chúng tôi truy cập thuộc tính StudentAddress của đối tượng sinh viên đầu tiên:
exec sp_executesql N'SELECT
[Extent1].[StudentID] AS [StudentID],
[Extent1].[Address1] AS [Address1],
[Extent1].[Address2] AS [Address2],
[Extent1].[City] AS [City],
[Extent1].[State] AS [State]
FROM [dbo].[StudentAddress] AS [Extent1]
WHERE [Extent1].[StudentID] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=1
Vô hiệu hóa lazy loading
Chúng ta có thể vô hiệu hóa lazy loading cho một thực thể cụ thể hoặc một Context. Để tắt lazy loading cho một thuộc tính cụ thể, đừng khai báo từ khóa virtual
. Để tắt lazy loading cho tất cả các thực thể trong Context, thiết lập thuộc tính cấu hình của nó thành false.
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;
using System.Linq;
public partial class SchoolDBEntities : DbContext
{
public SchoolDBEntities(): base("name=SchoolDBEntities")
{
this.Configuration.LazyLoadingEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
Quy tắc lazy loading:
- context.Configuration.ProxyCreationEnables phải là true.
- context.Configuration.LazyLoadingEnables phải là true.
- Thuộc tính Navigation nên được định nghĩa là
public
,virtual
. Context sẽ KHÔNG lazy loading nếu thuộc tính không được định nghĩa làvirtual
.