我有以下型號。在使用find方法從數據庫獲取數據時,用子實體加載父實體的更好方法是什麼?
上級實體:
public class Client
{
public int Id { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public DateTime DateOfBirth { get; set; }
public Address Address { get; set; }
}
子實體:
public class Address
{
public int Id { get; set; }
public string FirstLine { get; set; }
public string SecondLine { get; set; }
public string Province { get; set; }
}
現在,當我嘗試使用Find方法獲取數據時,地址實體為null,但是當我簽入DB數據時,Child表中也存在該ID。
referenceContext.Clients.Find(client.Id);
有辦法克服嗎?當我獲取父對象時,子實體的值也隨父一起加載。
注意:到目前為止,如果我使用了Include(i => i.Address)
,則只能再加載子實體。
我已經使用了Include,但是如果獲得父實體,是否還有其他選項可以加載子實體。
referenceContext.Clients.Where(c => c.IsActive.Equals(true))
.Include(i => i.Address).ToList();
如你所說:
注意:到目前為止,如果我使用了Include(i => i.Address) ,則只能再加載子實體。
是!這是在EF Core中加載相關數據的最佳方法。
您進一步說:
我已經使用了Include,但是如果獲得父實體,是否還有其他選項可以加載子實體。
是!有!這就是所謂的延遲加載 。要啟用延遲加載,必須將導航屬性設置為虛擬 ,如下所示:
public class Client
{
public int Id { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public DateTime DateOfBirth { get; set; }
public virtual Address Address { get; set; } // <-- Here it is
}
並且您必須按以下方式註冊DbConext
:
services.AddDbContext<BloggingContext>(
b => b.UseLazyLoadingProxies() // <-- Here is it is
.UseSqlServer(myConnectionString));
Microsoft.EntityFrameworkCore.Proxies nuget包中提供了UseLazyLoadingProxies()
方法。
注意:您不能禁用特定查詢的延遲加載。因此,使用Eager加載是在EF Core中加載相關數據的最佳方法。
在EF中,有一個使用.Include
的概念,稱為Eager Loading
。
MS Docs- 加載相關數據-EF Core
using MyContext context = new MyContext();
IList<Client> clients =
context.Clients
.Include(c => c.Address)
.Where(c => c.LastName == "patel")
.ToList();