这篇文章介绍了EntityFramework主从表数据加载方式,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
一、延迟加载: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);
}
}
二、贪婪加载: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主从表数据加载方式的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持得得之家。
织梦狗教程
本文标题为:Entity Framework主从表数据加载方式


基础教程推荐
猜你喜欢
- C# 解析XML和反序列化的示例 2023-04-14
- C#中的Linq to JSON操作详解 2023-06-08
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- Unity shader实现高斯模糊效果 2023-01-16