Entity Framework(03):Code First
1、延遲載入LazyLoading
使用延遲載入必須標註為virtual。
本例是標註Destination類裡的Lodgings為virtual。因為先發sql去查詢主鍵物件,然後根據主鍵id去從表裡查相關聯的資料。
private static void TestLazyLoading() { using (var context = new CodeFirst.DataAccess.BreakAwayContext()) { var canyon = (from d in context.Destinations where d.Name == "Grand Canyon" select d).Single(); var distanceQuery = from l in canyon.Lodgings //延遲載入canyon的所有.Lodgings where l.Name == "HuangShan Hotel" select l; foreach (var lodging in distanceQuery) Console.WriteLine(lodging.Name); } }
改進:在資料庫中操作,顯示載入
private static void QueryLodgingDistancePro() { using (var context = new CodeFirst.DataAccess.BreakAwayContext()) { var canyon = (from d in context.Destinations where d.Name == "Grand Canyon" select d).Single(); var lodgingQuery = context.Entry(canyon).Collection(d => d.Lodgings).Query();//接下來的查詢在資料庫中,包括Count()等 var distanceQuery = from l in lodgingQuery
where l.Name == "HuangShan Hotel"
select l;
foreach (var lodging in distanceQuery) Console.WriteLine(lodging.Name); } }
2、貪婪載入EagerLoading
/// </summary>
private static void TestEagerLoading()
{
using (var context = new CodeFirst.DataAccess.BreakAwayContext())
{
// var allDestinations = context.Destinations.Include(d => d.Lodgings);
var AustraliaDestination = context.Destinations.Include(d => d.Lodgings).Where(d => d.Name == "Bali");
//context.Lodgings.Include(l => l.PrimaryContact.Photo);
//context.Destinations.Include(d => d.Lodgings.Select(l => l.PrimaryContact));
//context.Lodgings.Include(l => l.PrimaryContact).Include(l => l.SecondaryContact);
foreach (var destination in AustraliaDestination)
{
foreach (var lodging in destination.Lodgings)
Console.WriteLine(" - " + lodging.Name);
}
}
}
/// <summary>
/// 顯示載入ExplicitLoading,查詢導航屬性為一個集合的
/// </summary>
private static void LoadRelateData()
{
using (var context = new CodeFirst.DataAccess.BreakAwayContext())
{
var canyon = (from d in context.Destinations where d.Name == "Grand Canyon" select d).Single();
context.Entry(canyon).Collection(d => d.Lodgings).Load(); //顯示載入
foreach (var lodging in context.Lodgings.Local)
Console.WriteLine(lodging.Name);
}
}
/// <summary>
/// 顯示載入ExplicitLoading,,查詢導航屬性為一個實體物件的
/// </summary>
private static void LoadPrimaryKeyData()
{
using (var context = new CodeFirst.DataAccess.BreakAwayContext())
{
var lodging = context.Lodgings.First();
context.Entry(lodging).Reference(l => l.Destination).Load();
foreach (var destination in context.Destinations.Local) //遍歷的是記憶體中的Destinations資料
Console.WriteLine(destination.Name);
}
}