Entity Framework主從表數據加載方式
更新時間:2022年06月13日 14:38:13 作者:springsnow
這篇文章介紹了Entity Framework主從表數據加載方式,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
一、延遲加載:LazyLoading
使用延遲加載,關聯(lián)的實體必須標注為virtual。
本例是標注Destination類里的Lodgings為virtual。因為先發(fā)sql去查詢主鍵對象,然后根據主鍵id去從表里查相關聯(lián)的數據。
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);
}
}二、貪婪加載:EagerLoading
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);
}
}
}三、顯示加載:ExplicitLoading
1、查找導航屬性為一個集合的
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);
}
}2、查找導航屬性為一個實體對象的
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);
}
}到此這篇關于Entity Framework主從表數據加載方式的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
C#中static void Main(string[] args) 參數示例詳解
這篇文章主要介紹了C#中static void Main(string[] args) 參數詳解,本文通過具體示例給大家介紹的非常詳細,需要的朋友可以參考下2017-03-03
C#/VB.NET實現(xiàn)在Word中插入或刪除腳注
腳注,是可以附在文章頁面的最底端的,對某些東西加以說明,印在書頁下端的注文。這篇文章將為您展示如何通過C#/VB.NET代碼,以編程方式在Word中插入或刪除腳注,需要的可以參考一下2023-03-03

